LWood
LWood

Reputation: 457

Specify mocked method's return value entirely regardless of parameters

Say I have a mock that contains a method public int Add(int, int) and I want the mock to return 5 is there way to specify that any call on AddTwoNumbers returns 5?

I already know I can use

mock.Setup(n => n.Add(It.IsAny<int>(), It.IsAny<int>()).Returns(5);

but if the add method changes to use floats, or more than two ints then tests using this break whereas being able to say 'all calls to Add return 5' would help with decoupling the tests.

Upvotes: 3

Views: 864

Answers (1)

Patrick Quirk
Patrick Quirk

Reputation: 23757

No, you cannot do this with Moq. The only API Moq exposes to specify the return the value of a method is the one you've shown. And obviously performing this setup requires the type parameters to match in order to compile. I think you're looking for a more loosely-typed API, something like:

mock.SetupMethodsNamed("Add").Returns(5);

If this is what you're looking for, feel free to open an issue with the Moq project; they're generally pretty open to suggestions and may be able to point out issues with this approach or why it isn't implemented.

However, I do not see any real benefit of doing this. If you're trying to protect your code from future changes, then how can you know that 5 will always be a sensible return type? If you're just trying to save some work (i.e. set up the int overload and the float overload in one shot), then just write a method to do them both and be done with it.

Upvotes: 4

Related Questions