DEV Community 👩‍💻👨‍💻

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

Moq: How to specify the argument with detail condition when mock a method?

This is my own note to remember how we can pass argument to mocked method in various ways.

Method to mock

I mock following service as an example, though this does nothing anyway.

public class DummyService
{
    public virtual string DummyMethod(string input)
    {
        return input;
    }
}
Enter fullscreen mode Exit fullscreen mode

Mock method with any value

We can use It.IsAny<T> to mock the method which accepts any value of T.

[Fact]
public void Test()
{
    Mock<DummyService> mockedDummyService = new();
    mockedDummyService.Setup(x => 
        x.DummyMethod(It.IsAny<string>())).Returns("dummy result");
}
Enter fullscreen mode Exit fullscreen mode

Mock method with specify value

We can pass actual value to mock the method which triggered only when the argument exactly matches.

[Fact]
public void Test()
{
    Mock<DummyService> mockedDummyService = new();
    mockedDummyService.Setup(x => 
        x.DummyMethod("testInput")).Returns("dummy result");
}
Enter fullscreen mode Exit fullscreen mode

Mock method with more detail condition

Or, we can specify more detail condition by using It.Is<T>(Func<T, bool>). The method will be triggered when I pass string such as MyInput, MyValue, etc.

[Fact]
public void Test()
{
    Mock<DummyService> mockedDummyService = new();
    mockedDummyService.Setup(x => 
        x.DummyMethod(It.Is<string>(x=>x.StartsWith("My")))).Returns("dummy result");
}
Enter fullscreen mode Exit fullscreen mode

And more

Moq.It has way more methods to control input patterns.

Image description

Top comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.