c# - 在其构造函数中从 session 中设置项目的模拟对象

标签 c# .net moq

我有一个第 3 方类型 BillingAddress,在反编译时我注意到它在其构造函数(来自 session )中设置了一些属性。我想模拟这种类型并将其发送到实用程序函数:

// need to be able to unit test this method
public static ShippingAddress Convert(BillingAddress billingAddress){
   var sAddress = new ShippingAddress();
   sAddress.City = billingAddress.City;
   // setting several shipping address properties
   //...
}

我无法创建 BillingAddress 的新实例,因为它是 session 构造函数代码(当我执行 new BillingAddress() 时它抛出异常 - 因为它仅在特定上下文中有效)

第三方库的反编译代码:

public BillingAddress(); // calls base() => gets session stuff
protected BillingAddress(SerializationInfo info, StreamingContext context);

因此,我正在尝试模拟 BillingAddress。这可能吗?怎么办?

我试过这个:

...
Mock<BillingAddress> m = new Mock<BillingAddress>();
var sAddress = Converter.Convert(c, m.Object);

我得到:

An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code

也试过这个:

var ac = new Mock<BillingAddress>(MockBehavior.Loose, new object[] { new Mock<SerializationInfo>(), new StreamingContext()});

同样的错误

更新:

BillingAddress 的构造函数:

// Decompiled code
public BillingAddress()
      : base(OrderContext.Current.MetaClass)
    {

有什么方法可以模拟 BillingAddress() => 以便在调用基础时注入(inject) OrderContext 的模拟?这样的事情可能吗?

OrderContext 是一个具有静态实例(当前)属性的公共(public)类。

最佳答案

I have a 3rd party type BillingAddress which when decompiled I noticed sets some properties in it's constructor (from session). I would like to mock such type and send it to a utility function.

如果您没有权利或不能更改 BillingAddress 的代码,因为它是第三方 API,那么只需创建一个包装它的新类来隐藏它。

public class BillingAddressWrapper
{
     private BillingAddress _billingAddress;

     public string City 
     {
          get { return _billingAddress.City; }
     }

     // Creatae properties that wrap BillingAddress properties as much as you want.
}

有了新类(class),您将拥有做您想做的事的所有能力,为了测试目的而模拟它只是其中之一。

在编写应用程序代码时,请始终避免绑定(bind)到第三方 API。为什么?因为它们中的大多数都为您提供了您想要在应用程序中使用的东西的特定实现。想象一下,在未来,如果您不得不选择另一个第三方 API 来替换实际的 API,因为它已经过时或没有更多的 API 支持,您将浪费大量时间来迁移到新的 API。

关于c# - 在其构造函数中从 session 中设置项目的模拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383307/

相关文章:

.net - Linq to Xml:异常-名称中不能包含''字符,十六进制值0x20

c# - 如何通过场景名称获取场景中的游戏对象列表,但只能获取一次?

c# - 在机器范围内以编程方式设置环境变量并发送设置更改消息

c# - c#中的对象克隆

c# - automapper - 如何映射对象列表

c# - 依赖注入(inject)解析和单元测试

c# - 如何在 Moq 中使用 lambda 语法设置现有模拟?

c# - xUnit 和 Moq 不支持 async - await 关键字

墨青MVVM Light的IMessenger

c# - 无法从 docker 运行 asp.net 5