Search code examples
c#mockingnunitmoq

Is there any more succinct way to stub values in C# unit tests?


Coming from a Kotlin/Groovy/Spock background, I found it very straightforward to stub a value for specific arguments:

something.someMethod(1) >> "Stubbed Return Value"

Entering the C# / Moq world and needing to do this frequently for tests, I seem to be stuck with comparatively verbose code like:

somethingMock.Setup(x => x.SomeMethod(It.Is<int>(x => x == 1))).Returns("Stubbed Return value");

This is quite unwieldy.

Is there a better / more succinct way I'm missing for doing this in C#?


Solution

  • It.Is<int>(x => x == 1) can be written as just 1. It.Is is useful once you want to perform expressions, but for literal values you don't need it. Just be careful when starting to compare with reference types instead of value types.

    An example of where you could use It.Is:

    somethingMock
        //I'm only interested in the Id of the instance
        .Setup(x => x.SomeMethod(It.Is<Person>(x => x.Id == 1)))
        .Returns("Stubbed Return value");