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?
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
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.
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 .
Verifies that all verifiable expectations have been met.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With