首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Moq,如何使用私有构造函数moq对象?

Moq,如何使用私有构造函数moq对象?
EN

Stack Overflow用户
提问于 2018-12-12 23:27:39
回答 1查看 1.5K关注 0票数 3

我有这个类的层次结构

代码语言:javascript
复制
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; 
    }
}

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

代码语言:javascript
复制
 clientMock = new Mock<Client>();
 clientMock.SetupGet(prop => prop.Client).Returns(1);

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

例外:

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-13 00:18:52

考虑到Order当前的定义,没有一种简单的方法可以让它被嘲笑。

尝试通过protected构造函数将所需的参数传递给mock来创建mock

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53746280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档