Search code examples
c#mockingmoqstubbingmoq-3

MOQ stubbing property value on "Any" object


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?


Solution

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