Lesson 39 of 93 · 6 min read · Updated

Moq Basics: Creating and Configuring Test Doubles with Setup, It.IsAny and It.Is

Moq is the most widely used mocking library for .NET. It creates a runtime implementation of an interface, lets you decide what each method returns, and records every call. This lesson covers the three basic steps: create a mock, configure it with Setup, and inject mock.Object into the class under test. It also explains how argument matchers decide whether a test can catch a wrong value, and when MockBehavior.Strict helps.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. FluentAssertions 7.2.2
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0

Create, Configure, Inject

The system under test is a CheckoutService that depends on IPaymentGateway and ICouponRepository. A small helper creates the mocks and the service so each test starts from the same place.

M05.TestableDesign.Tests/MoqBasicsTests.cs

/// <summary>
/// Three steps:
/// 1) var mock = new Mock<IInterface>();
/// 2) mock.Setup(x => x.Method(...)).Returns(...);
/// 3) Inject mock.Object into the SUT.
///
/// Argument matchers:
/// It.IsAny<T>() -> "any value at all"
/// It.Is<T>(predicate) -> "a value that satisfies this condition"
///
/// Preference: keep the matcher as narrow as is MEANINGFUL.
/// If you write It.IsAny everywhere, the test will not notice a wrong argument.
/// </summary>
public class MoqBasicsTests
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

/// <summary>Collects the shared test setup in one place.</summary>
private static (CheckoutService Sut, Mock<IPaymentGateway> Gateway, Mock<ICouponRepository> Coupons)
CreateSut(FakeTimeProvider? clock = null)
{
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

var sut = new CheckoutService(
gateway.Object,
coupons.Object,
clock ?? new FakeTimeProvider(Now),
NullLogger<CheckoutService>.Instance);

return (sut, gateway, coupons);
}

new Mock<IPaymentGateway>() builds a proxy class at runtime. The Mock<T> object is the control panel you configure and inspect. gateway.Object is the actual IPaymentGateway instance that the service receives. Mixing these two up is the most common beginner error: the service needs .Object, while Setup and Verify are called on the mock itself.

The helper returns the mocks as well as the service, so each test can configure only the calls it cares about.

Configuring a Return Value

Setup takes a lambda that describes a call. ReturnsAsync gives the value for a method that returns Task<T>.

M05.TestableDesign.Tests/MoqBasicsTests.cs

[Fact]
public async Task PayAsync_WhenAuthorizationIsApproved_ReturnsSuccess()
{
// Arrange
var (sut, gateway, _) = CreateSut();

gateway
// It.IsAny: the VALUE of the amount does not matter in this test.
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-123"));

// Act
var result = await sut.PayAsync(Money.Try(1_000m), couponCode: null);

// Assert - we check the OUTPUT first.
result.IsSuccessful.Should().BeTrue();
result.Reference.Should().Be("AUTH-123");
result.Charged.Should().Be(Money.Try(1_000m));
}

Notice that the optional CancellationToken parameter must appear in the expression. A Moq setup expression is a lambda tree, and expression trees cannot use optional parameters, so every argument has to be listed.

The decline path uses the same shape with a different return value. Here the mock acts as a stub: it feeds an input into the service, and the test checks the service's output.

M05.TestableDesign.Tests/MoqBasicsTests.cs

[Fact]
public async Task PayAsync_WhenGatewayDeclines_ReturnsFailureWithReason()
{
var (sut, gateway, _) = CreateSut();

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Decline("Yetersiz bakiye"));

var result = await sut.PayAsync(Money.Try(1_000m), couponCode: null);

result.IsSuccessful.Should().BeFalse();
result.Failure.Should().Be("Yetersiz bakiye");
}

The decline reason, "Yetersiz bakiye", means "insufficient funds". The test asserts that the service passes it through unchanged.

Narrow Matchers Catch Wrong Arguments

It.IsAny<T>() matches every value. That is right when the value does not matter. When it does matter, use It.Is<T>(predicate).

M05.TestableDesign.Tests/MoqBasicsTests.cs

[Fact]
public async Task PayAsync_WithValidCoupon_AuthorizesDiscountedAmount()
{
var (sut, gateway, coupons) = CreateSut();

coupons
.Setup(x => x.FindAsync("BAHAR10", It.IsAny<CancellationToken>()))
.ReturnsAsync(Coupons.TenPercentValid());

// It.Is: here the amount MATTERS. 1000 with a 10% discount must be 900.
// Because of this narrowing, if the discount is calculated wrongly the Setup
// does not match and the mock returns its default (null/false) -> the test fails.
gateway
.Setup(x => x.AuthorizeAsync(
It.Is<Money>(m => m.Amount == 900m && m.Currency == "TRY"),
It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-900"));

var result = await sut.PayAsync(Money.Try(1_000m), "BAHAR10");

result.IsSuccessful.Should().BeTrue();
result.Charged.Amount.Should().Be(900m);
}

Consider what happens if this test used It.IsAny<Money>() instead. The gateway would approve any amount, including 1000 or 0. The Charged.Amount assertion would still catch a wrong discount here, but in a test that only checks IsSuccessful, the wrong amount would go unnoticed. With It.Is, a wrong amount means the setup does not match. A loose mock then returns its default value for the call, and the test fails.

The coupon setup uses a literal argument, "BAHAR10". A literal is shorthand for "equal to this value". If the service passed a different code, FindAsync would return the default and the discount would not apply.

The matcher choice is the key skill here. For each argument, ask: "would the service be wrong if it passed a different value?" If yes, constrain it with a literal or It.Is. If no, use It.IsAny so the test does not break for reasons the scenario does not cover. Constraining everything makes tests brittle. Constraining nothing makes them blind.

Loose and Strict Behavior

By default a Moq mock is loose: any call without a matching setup returns a default value. For Task<T> methods Moq returns a completed task, not null. A strict mock throws on any call that has no setup.

M05.TestableDesign.Tests/MoqBasicsTests.cs

[Fact]
public void MockBehaviorStrict_FailsOnUnconfiguredCalls()
{
// MockBehavior.Loose (default): unconfigured calls return a default value.
var loose = new Mock<ICouponRepository>();
loose.Object.FindAsync("YOK").Should().NotBeNull();

// MockBehavior.Strict: every unconfigured call THROWS.
// Benefit: catches forgotten setups early.
// Cost: ties the test tightly to implementation details. Use with care.
var strict = new Mock<IPaymentGateway>(MockBehavior.Strict);
Action act = () => _ = strict.Object.AuthorizeAsync(Money.Try(1m));

act.Should().Throw<MockException>();
}

Strict mocks look safer, but they force every test to list every call the service makes, even calls the scenario does not care about. When the implementation adds a harmless call, all strict tests fail. Prefer loose mocks and assert on outcomes. Use strict mode only for a boundary where any unexpected call is itself a bug.

Summary

  1. Create with new Mock<T>(), configure with Setup(...).ReturnsAsync(...), and inject mock.Object.
  2. List every argument in a setup expression, including optional CancellationToken parameters.
  3. Use It.IsAny<T>() when the value does not matter and It.Is<T>(...) or a literal when it does.
  4. A loose mock returns defaults for unmatched calls, so a narrow matcher turns a wrong argument into a failing test.
  5. MockBehavior.Strict catches forgotten setups but couples tests to implementation details; use it rarely.