我对Moq完全陌生,现在正在尝试为System.Reflection.Assembly类创建一个mock。我使用的是以下代码:
var mockAssembly = new Mock<Assembly>();
mockAssembly.Setup( x => x.GetTypes() ).Returns( new Type[] {
typeof( Type1 ),
typeof( Type2 )
} );但是当我运行测试时,我得到了下一个异常:
System.ArgumentException : The type System.Reflection.Assembly
implements ISerializable, but failed to provide a deserialization
constructor
Stack Trace:
at
Castle.DynamicProxy.Generators.BaseProxyGenerator.VerifyIfBaseImplementsGetObjectData(Type
baseType)
at
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[]
interfaces, ProxyGenerationOptions options)
at Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxy(Type
classToProxy, Type[] additionalInterfacesToProxy,
ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type
classToProxy, Type[] additionalInterfacesToProxy,
ProxyGenerationOptions options, Object[] constructorArguments,
IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy[T](ICallInterceptor
interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__0()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock`1.get_Object() 你能推荐给我用Moq模拟ISerializable类(比如System.Reflection.Assembly)的正确方法吗?
提前感谢!
发布于 2010-04-23 18:14:41
问题不在ISerializable接口。你可以模仿 ISerializable类。
请注意异常消息:
类型System.Reflection.Assembly实现了ISerializable,但未能提供反序列化构造函数
问题是,Assembly没有提供反序列化构造函数。
发布于 2013-07-10 09:04:35
正如前面所解释的,问题在于Assembly没有公开反序列化构造函数。然而,这并不意味着它不能做到。
根据您的示例,使用Moq的解决方案将是:
var mock = new Mock<_Assembly>();
result.Setup(/* do whatever here as usual*/);请注意,要使用_Assembly,您需要引用System.Runtime.InteropServices
发布于 2010-05-15 03:40:14
您可以尝试创建动态程序集并从中构建,而不是使用mock。
var appDomain = AppDomain.CurrentDomain;
var assembly = appDomain.DefineDynamicAssembly(new AssemblyName("Test"), AssemblyBuilderAccess.ReflectionOnly);https://stackoverflow.com/questions/2696236
复制相似问题