I'm using the Setup()
method to set up the behaviour of a mocked instance of an interface.
The method I'm setting up (let's call it DoSomething()
) accepts an instance of a class (let's call the class Foo
).
Foo foo = // Existing foo instance
Mock<IMyInterface> mock = new Mock<IMyInterface>();
mock.Setup(x => x.DoSomething(foo)).Returns(1);
The problem I'm having is that when I use the mock, it never matches the setup, so never returns 1.
Can anyone help? How does Moq determine whether the parameters provided to a set up method are equal or not?
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.
Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo. DoSomething("ping")). Returns(true);
Verifies that all verifiable expectations have been met.
CallBase , when initialized during a mock construction, is used to specify whether the base class virtual implementation will be invoked for mocked dependencies if no setup is matched. The default value is false . This is useful when mocking HTML/web controls of the System.
The answer to my question is that Moq uses .Equals
to determine whether parameters to set up methods are equal.
For a slightly more detailed answer, Moq uses the ConstantMatcher
(link is to current latest version 4.13.1). The implementation of that matcher is
object.Equals
object.Equals
failed and value implements IEnumerable
use SequenceEqual<object>
(which uses object.Equals
for each element)false
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