Lesson 39 of 93 · 6 min read · Updated
Moq Basics: Creating and Configuring Test Doubles with Setup, It.IsAny and It.Is
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- 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
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
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
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
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
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
- Create with
new Mock<T>(), configure withSetup(...).ReturnsAsync(...), and injectmock.Object. - List every argument in a setup expression, including optional
CancellationTokenparameters. - Use
It.IsAny<T>()when the value does not matter andIt.Is<T>(...)or a literal when it does. - A loose mock returns defaults for unmatched calls, so a narrow matcher turns a wrong argument into a failing test.
MockBehavior.Strictcatches forgotten setups but couples tests to implementation details; use it rarely.