C# 最小起订量存根地产价值;任何;对象

C# 最小起订量存根地产价值;任何;对象,c#,mocking,moq,stubbing,moq-3,C#,Mocking,Moq,Stubbing,Moq 3,我正在编写一些代码,这些代码遵循一种模式,将所有参数封装到一个方法中,作为一个“请求”对象,并返回一个“响应”对象。然而,当涉及到MOQ的嘲笑时,这产生了一些问题。例如: public class Query : IQuery { public QueryResponse Execute(QueryRequest request) { // get the customer... return new QueryResponse { Custome

我正在编写一些代码,这些代码遵循一种模式,将所有参数封装到一个方法中,作为一个“请求”对象,并返回一个“响应”对象。然而,当涉及到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});
var客户=新客户();
var key=“某物”;
var query=new Mock();
//我想做这样的事情(但这行不通)
//也就是说,我不在乎传递的请求对象是什么,但它必须具有我想要给它的键值
query.Setup(q=>q.Execute(It.IsAny().Key=Key)).Returns(newqueryresponse{Customer=Customer});

我想要的在MOQ中可能吗?

您正在寻找的
it.Is
方法,您可以在其中为参数指定任何匹配器函数(
Func

例如,检查密钥:

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

我想你可以用自定义匹配器来实现这一点

发件人:

注意:我还没有尝试过这个代码,所以如果它完全崩溃,请原谅我

哦,对于一些稍微相关的自我宣传:正是这种复杂性让我对Moq和其他模拟工具感到不安。这就是为什么我创建了一个模拟库,允许您使用普通代码检查方法参数:。这是在一个主要的重构(重命名)过程的中间,所以你可能需要屏住呼吸。尽管如此,我还是很高兴听到你对它的看法

编辑:哦,@nemesv击败了我,并给出了(可能)更好的答案。好吧

// custom matchers
mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();
...
public string IsLarge() 
{ 
  return Match.Create<string>(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}
public QueryRequest CorrectKey(string key)
{
    return Match.Create<QueryRequest>(qr => qr.Key == key);
}
_query.Setup(q => q.Execute(CorrectKey(key))).Returns(new QueryResponse {Customer = customer});