unit-testing - 最小起订量,如何使用私有(private)构造函数最小起订量对象?

标签 unit-testing testing mocking moq

我有这个类层次结构

public class Order
{  
    private Client _client;
    public virtual Client { get => _client; }

    private OrderNumber _orderNumber;
    public virtual OrderNumber OrderNumber { get => _orderNumber; }

    private ShippingDetails _shippingDetails;
    public virtual ShippingDetails ShippingDetails { get => _shippingDetails; }

    private IList<Product> _products;
    protected internal virtual IEnumerable<Product> Products { get => _products; }


    public Order() { }

    public virtual void CreateDraftForClient(int id)
    {
         /// => business rule validation of value 

         _client= new Client(id);

          /// => event     
     }
}

public class Client
{
    private int _id;
    public virtual int Id { get => _id; }

    private Client() { }
    protected internal Client(int id) 
    {
        SetId(id);
    }

    private void SetId(int id)
    {
        _id = id; 
    }
}

并希望创建一个完全初始化的订单模拟

 clientMock = new Mock<Client>();
 clientMock.SetupGet(prop => prop.Client).Returns(1);

 orderMock = new Mock<Order>();
 orderMock.SetupGet(prop => prop.Client).Returns(orderMock.Object);

异常:

Message: System.AggregateException : One or more errors occurred. (Can not instantiate proxy of class: Client. Could not find a parameterless constructor.) (The following constructor parameters did not have matching fixture data: eRxTestSetup testSetup)
---- Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Client. Could not find a parameterless constructor.
---- The following constructor parameters did not have matching fixture data: eRxTestSetup testSetup

有什么方法可以在不改变客户端结构的情况下做到这一点?或者,如果没有,我还有哪些其他选择?

最佳答案

Order 没有简单的方法可以根据其当前定义进行模拟。

通过将所需的参数传递给模拟,尝试通过 protected 构造函数创建模拟

int id = 1;
var clientMock = new Mock<Client>(id);
clientMock.SetupGet(prop => prop.Id).Returns(id);

var orderMock = new Mock<Order>();
orderMock.SetupGet(prop => prop.Client).Returns(clientMock.Object);

关于unit-testing - 最小起订量,如何使用私有(private)构造函数最小起订量对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53746280/

相关文章:

laravel - 如何在 phpunit 测试中使用带有模拟缓存的缓存标签?

python - 杀死模拟对象 : A Python Story

javascript - 如何在 Intellij 或 Webstorm 中使用 Karma & Jasmine 调试 JS 单元测试

node.js - 如何使用nodejs和mocha模拟另一个lambda函数内的aws lambda函数调用

c# - 使用 Moq 模拟 NHibernate ISession

java - 测试 AbstractProcessor(Java 在编译时的注解处理)

web-services - 修复 SoapUI 中的 "Missing SOAP Operations in Project"错误

javascript - 自动化应用程序测试 (phantomjs) 和 merge 分支

node.js - 模拟存储库,然后换成 Node.js 中的实际实现

java - 测试根据输入调用内部方法的公共(public)方法