Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
bytedev Avatar asked Jun 06 '13 12:06

bytedev


People also ask

How do you set a mock object property?

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.


1 Answers

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});
like image 97
nemesv Avatar answered Oct 10 '22 04:10

nemesv