我有这个课程层次结构
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
有什么办法可以做到而不必更改客户端的结构?否则,我还有什么其他选择?
答案 0 :(得分:2)
考虑到Order
当前的定义,没有简单的方法。
尝试通过将所需的参数传递给模拟来通过受保护的构造函数创建模拟
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);