David
David

Reputation: 16120

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?

Upvotes: 14

Views: 3353

Answers (2)

Simon Touchtech
Simon Touchtech

Reputation: 408

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

Upvotes: 6

David
David

Reputation: 16120

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

Upvotes: 9

Related Questions