如何用Moq模拟ISerializable类?
我完全是Moq的新手,现在正试图为 System.Reflection.Assembly
类创建一个模拟。我使用此代码:如何用Moq模拟ISerializable类?
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()
你能reccomend我起订量嘲笑ISerializable
类 (如System.Reflection.Assembly
)的正确途径。
在此先感谢!
该问题与ISerializable接口不兼容。你可以模拟ISerializable类。
注意异常消息:
类型System.Reflection.Assembly 实现了ISerializable,但未能 提供反序列化 构造
问题是,大会不提供反序列化构造函数。
而不是一个模拟,你可以尝试创建一个动态组装和建立。
var appDomain = AppDomain.CurrentDomain;
var assembly = appDomain.DefineDynamicAssembly(new AssemblyName("Test"), AssemblyBuilderAccess.ReflectionOnly);
正如已经解释过的,问题在于Assembly没有公开反序列化构造函数。这并不意味着它不能完成。
使用起订量的溶液按你的例子是:
var mock = new Mock<_Assembly>();
result.Setup(/* do whatever here as usual*/);
注意使用_Assembly
你需要引用System.Runtime.InteropServices
System.Reflection.Assembly是抽象的,所以你不能创建一个新的实例。但是,你可以创建一个测试类,并且可以模拟它。
实施例:
[TestMethod] public void TestSomethingThatNeedsAMockAssembly() { string title = "title";
var mockAssembly = new Mock();
mockAssembly.Setup(a => a.GetCustomAttributes(It.Is(s => s == Type.GetType("System.Reflection.AssemblyTitleAttribute")), It.IsAny())).Returns(new System.Attribute[] { new AssemblyTitleAttribute(title) });var c = new ClassThatTakesAssemblyAndParsesIt(mockAssembly.Object); Assert.IsTrue(c.AssemblyTitle == title); //etc } public class TestAssembly : Assembly { public TestAssembly() { //could probably do something interesting here } }
+1使用RhinoMocks,'_Assembly'技巧对我不起作用,并且我最终使用了它。只是在寻找一个问题来分享这些知识。 – mao47 2013-11-12 21:26:53
好,感谢。但是,你能否建议在这种情况下如何使用Moq提供反序列化构造函数。 – sam 2010-04-23 20:27:17
你不能 - Assembly没有任何可访问的构造函数,因此当使用Moq时它是unmockable:| – 2010-04-24 08:24:37
您不需要提供反序列化构造函数来模拟Assembly。您可以模拟互操作_Assembly类并在需要时转换为Assembly。 – nathanchere 2013-07-10 01:05:41