c# – “任意”对象上的MOQ存根属性值

前端之家收集整理的这篇文章主要介绍了c# – “任意”对象上的MOQ存根属性值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究一些代码,这些代码遵循将方法的所有参数封装为“请求”对象并返回“响应”对象的模式.但是,在使用MOQ进行模拟时,这会产生一些问题.例如:
public class Query : IQuery
{
    public QueryResponse Execute(QueryRequest request)
    {
        // get the customer...
        return new QueryResponse { Customer = customer };
    }
}

public class QueryRequest
{
    public string Key { get; set; }
}

public class QueryResponse
{
    public Customer Customer { get; set; }
}

…在我的测试中,我希望存根查询以在给出密钥时返回客户

var customer = new Customer();
var key = "something";
var query = new Mock<ICustomerQuery>();

// I want to do something like this (but this does not work)
// i.e. I dont care what the request object that get passed is in but it must have the key value I want to give it

query.Setup(q => q.Execute(It.IsAny<QueryRequest>().Key = key)).Returns(new QueryResponse {Customer = customer});

MOQ中我想要的是什么?

解决方法

你正在寻找它It.Is< T>方法,您可以为参数指定任何匹配器函数(Func< T,bool>).

例如检查密钥:

query.Setup(q => q.Execute(It.Is<QueryRequest>(q => q.Key == key)))
     .Returns(new QueryResponse {Customer = customer});

猜你在找的C#相关文章