c# - "Any"对象上的 MOQ stub 属性值

标签 c# mocking moq stubbing moq-3

我正在编写一些代码,这些代码遵循将方法的所有参数封装为“请求”对象并返回“响应”对象的模式。然而,这在使用 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; }
}

...在我的测试中,我想 stub 查询以在给定 key 时返回客户

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});

我想要的最小起订量是否可行?

最佳答案

你在找什么It.Is<T>方法,您可以在其中为参数指定任何匹配器函数(Func<T, bool>)。

例如检查 key :

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

关于c# - "Any"对象上的 MOQ stub 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16962526/

相关文章:

c# - async/await 和 Parallel.For 循环

c# - 使用 XmlDictionaryWriter.CreateBinaryWriter 和 XmlDictionary 编写紧凑的 xml

c# - 如何在 C# 中将一个字符串与大量预定义字符串进行比较?

.net - 验证使用 Moq 调用 protected 方法的次数

c# - SetupSet 'forgets'方法设置的使用

c# - 即使调用应用程序关闭,删除功能也会删除

java - 如何在 Java 中创建 “FTPS” 模拟服务器以进行单元测试,出现错误 - javax.net.ssl.SSLException : 502 Command not implemented: AUTH

javascript - 使用 Jest 在另一个模块的依赖项中断言函数调用

c# - 在 C# 中模拟局部变量

asp.net-mvc - ASP.NET MVC 单元测试 - session