如何使用Moq模拟ISerializable类?

sam*_*sam 6 .net moq serializable

我完全是Moq的新手,现在正试图为System.Reflection.Assembly课堂创建一个模拟器 .我正在使用此代码:

var mockAssembly = new Mock<Assembly>(); 
mockAssembly.Setup( x => x.GetTypes() ).Returns( new Type[] { 
    typeof( Type1 ), 
    typeof( Type2 ) 
} );
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,我得到下一个异常:

System.ArgumentException : The type System.Reflection.Assembly 
implements ISerializable, but failed to provide a deserialization 
constructor 
Stack Trace: 
   at 
Castle.DynamicProxy.Generators.BaseProxyGenerator.VerifyIfBaseImplementsGet­ObjectData(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() 
Run Code Online (Sandbox Code Playgroud)

你能告诉我使用Moq 模拟ISerializable类(如System.Reflection.Assembly)的正确方法吗?

提前致谢!

Chu*_*nce 5

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 } }
Run Code Online (Sandbox Code Playgroud)


Krz*_*mic 2

问题不在于 ISerialized 接口。您可以模拟 ISerialized 类。

注意异常消息:

System.Reflection.Assembly 类型实现了 ISerialized,但未能提供反序列化构造函数

问题是,Assembly 不提供反序列化构造函数。