我正在研究一些代码,这些代码遵循将方法的所有参数封装为“请求”对象并返回“响应”对象的模式.但是,在使用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中我想要的是什么?
解决方法
@H_301_13@ 你正在寻找它It.Is< T>方法,您可以为参数指定任何匹配器函数(Func< T,bool>).例如检查密钥:
query.Setup(q => q.Execute(It.Is<QueryRequest>(q => q.Key == key))) .Returns(new QueryResponse {Customer = customer});