The value of the MQ stubbing property on the Any object

I am working on some code that follows a pattern to encapsulate all arguments into a method as a request object and return a response object. However, this has caused some problems when it comes to ridicule over MOQ. For instance:

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 request in order to return the client when the key is specified

 var customer = new Customer(); var key = "something"; var query = new Mock<ICustomerQuery>(); // I want to do something like this (but this does not work) // ie 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}); 

I want MOQ to be possible?

+6
source share
2 answers

What are you looking for for this It.Is<T> method, where you can specify any tag function ( Func<T, bool> ) for the argument.

For example, key verification:

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

I suspect you can do this with custom matches.

From moq QuickStart Page :

 // custom matchers mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>(); ... public string IsLarge() { return Match.Create<string>(s => !String.IsNullOrEmpty(s) && s.Length > 100); } 

I suspect you could do that. Create a method that uses Match.Create<QueryRequest> to match your key, for example

 public QueryRequest CorrectKey(string key) { return Match.Create<QueryRequest>(qr => qr.Key == key); } 

and then

 _query.Setup(q => q.Execute(CorrectKey(key))).Returns(new QueryResponse {Customer = customer}); 

Note. I have not tried this code, so forgive me if it completely breaks.

Oh, and for some of the slightly related ones, it’s just that kind of complexity that’s what bothers me about Moq and other mocking tools. That's why I created a ridiculous library that allows you to check the arguments of a method with regular code: http://github.com/eteeselink/FakeThat . This is in the middle of the main refactoring (and renaming) process, although you might want to hold your breath. However, I would be delighted that you think about it.

EDIT: Oh, @nemesv beat me up, with a (possibly) better answer. Good.

0
source

Source: https://habr.com/ru/post/946685/


All Articles