Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Moq to verify that a mocked method was called with specific values in a complex parameter?

So assume I am mocking the following class:

public class ClassAParams {     public int RequestedId { get; set; }     public string SomeValue { get; set; } }  public class ClassA {     public void ExecuteAction(ClassAParams executeParams) {} } 

Now say I have another class (let's call it ClassB) that I am creating a unit testing for, and I want to make sure that when ClassB.Execute() is called, that ClassB calls ClassA.ExecuteAction() but I want to make sure that the parameter it calls that method with has a ClassAParams.RequestedId value of 1.

Normally, I would handle this by doing myMock.Verify(x => x.ExecuteAction(new ClassAParams { RequestedId = 1, SomeValue = "something" }));

The problem is, I do not want to check the value of the SomeValue parameter, or any other ClassAParams properties in this unit test. The other properties will be checked in other unit tests, but having to verify that it's called with the correct properties in every unit test (even when I don't care in the scope of a specific unit tests) will make unit maintenance annoying.

Is there any way to use Moq to verify that the structure that gets passed into a mocked method only has certain properties as a specific value, and ignore the rest?

like image 586
KallDrexx Avatar asked Jun 11 '11 17:06

KallDrexx


People also ask

How can you check if a method was called using a mock?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

How can we use a Moq to check if a method is called with the correct parameters?

When you need to verify that the code under test called a method with the expected parameters, you can mock the method with Moq and use Verify() + It.Is<T>() to check the parameters passed in. Verify() asserts that the method call happened as expected with the specified parameters.

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for .

What does Moq verify do?

Verifies that all verifiable expectations have been met.


1 Answers

An overload exists for mock.Verify which allows you to test something. Here is an example that should work for your test.

classA.Verify(     a => a.ExecuteAction(         It.Is<ClassAParams>(p => p.RequestedId == 12)     ) ); 

Which means "For any ClassAParams passed as argument, verify RequestId equals 12".

like image 80
SandRock Avatar answered Oct 05 '22 10:10

SandRock