gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:26:37 27 4
gpt4 key购买 nike

我有这个类层次结构

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com