I'm working on some code that follows a pattern of encapsulating all arguments to a method as a "request" object and returning a "response" object. However, this has produced some problems when it comes to mocking with MOQ. For example:
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; }
}
... in my test I want to stub the query to return the customer when the key is given
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});
Is what I want possible in MOQ?
You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time. For more information about mock object behavior, see Specify Mock Object Behavior.
What you are looking for it the It.Is<T>
method where you can specify any matcher function (Func<T, bool>
) for the argument.
For example checking for the key:
query.Setup(q => q.Execute(It.Is<QueryRequest>(q => q.Key == key)))
.Returns(new QueryResponse {Customer = customer});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With