devlooped / moq

The most popular and friendly mocking framework for .NET
Other
5.92k stars 801 forks source link

Specify a mock return regardless of parameters passed into the method call #226

Closed LeahDWood closed 8 years ago

LeahDWood commented 8 years ago

Would it be possible to implement a feature that allows a test to contain a mock setup that specifies a return regardless of the passed in parameters, something along the lines of "mock.SetupMethodsNamed("Add").Returns(5);"?

I asked if the feature already existed here and was prompted to open an issue.

kzu commented 8 years ago

That's the purpose of It.IsAny.

See https://github.com/Moq/moq4/wiki/Quickstart#matching-arguments

LeahDWood commented 8 years ago

I know about It.IsAny already but that requires specifying per parameter. I was wondering if there is any possibility of a feature that allows similar functionality without relying on specifying each parameter via It.IsAny.

pjquirk commented 8 years ago

In other words, given these methods:

int Add(int x, int y);
float Add(float x, float y);
double Add(double x, double y);

And then performing a setup as mentioned:

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

Would be (more or less) equivalent to:

mock.Setup(m => m.Add(It.IsAny<int>(), It.IsAny<int>()).Returns((int)5);
mock.Setup(m => m.Add(It.IsAny<float>(), It.IsAny<float>()).Returns((float)5);
mock.Setup(m => m.Add(It.IsAny<double>(), It.IsAny<double>()).Returns((double)5);
LeahDWood commented 8 years ago

That's the idea exactly, thanks for the example.

kzu commented 8 years ago

I don't think there's a lot of value in that, especially since it will break badly if you add overloads of Add that have a different return value. And you lose the ability to refactor your APIs since now those "magic strings" will get out of date.

So, too many drawbacks to save a couple lines of code.

pjquirk commented 8 years ago

@kzu In general I agree, though the nameof operator addresses your second point.

kzu commented 8 years ago

That would only give you the name of one of the overloads. If you happen to rename the others, you won't notice.

On Mon, Dec 14, 2015 at 10:58 AM Patrick Quirk notifications@github.com wrote:

In general I agree, though the nameof operator addresses your second point.

— Reply to this email directly or view it on GitHub https://github.com/Moq/moq4/issues/226#issuecomment-164444411.

j03INTHECLOUD commented 3 years ago

This would really help for mocking Microsoft methods because they love to put in option params with a default of null

stakx commented 3 years ago

@j03INTHECLOUD there is nothing stopping you from creating an extension method on Mock<T> that, given a string methodName, will look for all methods of that name and create a setup for each of them, filling in It.IsAny<>() for all parameters. This doesn't need to be in the main library, though (and it won't be, since it goes counter to Moq's stated design goals).