Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a method with parameters

Tags:

c#

mocking

moq

I'm injecting a dependency CheckCompatibRepository. I'm mocking a method IsCompatible which has a list as 3rd parameter.

 var mockRepositoryCheckCompatib = new Mock<ICheckCompatibilityActDoer>();
            mockRepositoryCheckCompatib.Setup(c => c.IsCompatible(doer, activity, listActivitiesPreDispatched)).Returns(true);

The problem is the list. It's populated by the class I'm testing. Honnestly, I don't care about that parameter, I want to mock IsCompatible ignoring that parameter. Is that possible?

Otherwise, the mocking just won't catch the method calls. To ease things, I tried by sending the list as an injected dependency in my class. It works until the list starts being populated, then the mock stops catching the calls.

How would you mock this?

like image 571
Mathieu Avatar asked Dec 21 '22 00:12

Mathieu


1 Answers

Since you're using Moq, you're looking for the It.IsAny<T> method. Since you're changing the values of the list, passing it an object instance is not the right way to go as you would have to continually setup the Mock to handle the new parameter.

The following example will allow the mock to accept any parameter value of type List<T>. For the sake of this example, we will use List<int>.

 var mockRepositoryCheckCompatib = new Mock<ICheckCompatibilityActDoer>();
 mockRepositoryCheckCompatib.Setup(c => c.IsCompatible(doer, activity, It.IsAny<List<int>>())).Returns(true);

Edit: I didn't see bzlm's comment from earlier, which essentially answers the question. Please accept his answer if he posts one, I didn't mean to poach it.

like image 170
ahawker Avatar answered Dec 23 '22 14:12

ahawker