Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moq: When using Setup(), how is equality of method parameters determined?

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?

like image 246
David Avatar asked Nov 08 '12 15:11

David


People also ask

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 is setup in Moq?

Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo. DoSomething("ping")). Returns(true);

What does Moq verify do?

Verifies that all verifiable expectations have been met.

What is CallBase in Moq?

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.


2 Answers

The answer to my question is that Moq uses .Equals to determine whether parameters to set up methods are equal.

like image 96
David Avatar answered Sep 23 '22 15:09

David


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

  1. Use object.Equals
  2. If object.Equals failed and value implements IEnumerable use SequenceEqual<object> (which uses object.Equals for each element)
  3. If both of the above failed return false
like image 44
Simon Touchtech Avatar answered Sep 23 '22 15:09

Simon Touchtech