DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

5 1

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay