.net - 如何使用 Moq 模拟 ISerializable 类?

标签 .net moq serializable

我对 Moq 完全陌生,现在正在尝试为System.Reflection.Assembly类(class)。我正在使用这段代码:

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.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() 

你能推荐我模拟的正确方法ISerializable类(class)
(如 System.Reflection.Assembly )与最小起订量。

提前致谢!

最佳答案

System.Reflection.Assembly 是抽象的,因此您不能创建它的新实例。但是,您可以创建一个测试类并模拟它。

例子:

[测试方法]
公共(public)无效 TestSomethingThatNeedsAMockAssembly()
{
字符串标题=“标题”;
var mockAssembly = new Mock();
mockAssembly.Setup(a => a.GetCustomAttributes(It.Is(s => s == Type.GetType("System.Reflection.AssemblyTitleAttribute")), It.IsAny())).Returns(new System.Attribute[ ] { 新的 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 } }

关于.net - 如何使用 Moq 模拟 ISerializable 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2696236/

相关文章:

.net - 使用真实IP加密发送到托管在服务器上的WCF服务的消息

c# - 数据库中的重复项

c# - Moq - 模拟一个复杂的存储库方法 - 列出未返回的对象

entity-framework-4 - 如何 EF4 + Ninject + 起订量?

java - 是否可以自动序列化知道 .class 文件的对象

android - FasterXML Jackson ObjectMapper for .Net MVC4 JSON POST 结果类型对象

.net - 在 WPF MediaElement 中显示视频的第一帧

c# - 如何使用 Moq 模拟 IMongoCollection.Find

java - 如何在 List<Serializable> 内容 JaxB 中添加元素?

Java命名约定和serialVersionUID(常量小写)