Lesson 40 of 93 · 6 min read · Updated

Verifying Calls with Moq: Verify, Times and VerifyNoOtherCalls

Some behavior has no return value to assert on. When a checkout succeeds, the important effect is that money is captured from the customer's card exactly once. The only way to see that effect in a unit test is to ask the payment gateway double which calls it received. Moq does this with Verify and the Times options. This lesson shows how to write a few high-value verifications and why many low-value ones make tests fragile.

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

The Times Options

Verify takes the same kind of expression as Setup, plus a Times value that says how many matching calls are expected.

TimesMeaning
Times.Onceexactly one matching call
Times.Neverno matching call
Times.Exactly(n)exactly n calls
Times.AtLeastOnce()one or more calls
Times.Between(a, b, Range.Inclusive)a count in a range

If the count does not match, Verify throws a MockException. The message lists the expected call and every call the mock actually received, which makes failures easy to read.

One Valuable Verification: Capture Exactly Once

Double capture is a real production bug: the customer pays twice. That makes "capture was called once, with the right reference and amount" a verification worth writing.

M05.TestableDesign.Tests/MoqVerifyTests.cs

/// <summary>
/// Verify(expression, Times.Once) -> exactly 1 time
/// Times.Never / Exactly(n) / AtLeastOnce() / Between(...)
///
/// GOLDEN RULE: instead of MANY verifications of implementation details,
/// write FEW verifications of HIGH VALUE.
/// "Was the money captured exactly once?" -> valuable.
/// "Was the repository queried twice?" -> worthless and fragile.
/// </summary>
public class MoqVerifyTests
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

[Fact]
public async Task PayAsync_WhenApproved_CapturesExactlyOnceWithSameAmount()
{
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-77"));

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

await sut.PayAsync(Money.Try(500m), couponCode: null);

// ONE high-value verification: right reference, right amount, EXACTLY ONCE.
// Double capture is a real production bug - that is why Times.Once matters.
gateway.Verify(
x => x.CaptureAsync(
"AUTH-77",
It.Is<Money>(m => m.Amount == 500m),
It.IsAny<CancellationToken>()),
Times.Once);
}

The verification checks three things at once. The reference must be the one returned by authorization, "AUTH-77", so the capture applies to the right transaction. The amount must be 500, so the customer pays what was authorized. And the count must be one. The CancellationToken is not part of this scenario, so it uses It.IsAny.

Note that CaptureAsync returns a plain Task and has no setup. A loose mock returns a completed task for it, so the service can await it without any extra configuration.

Verifying That Something Did Not Happen

"Never called" is also a contract. When the gateway declines, the service must not capture anything.

M05.TestableDesign.Tests/MoqVerifyTests.cs

[Fact]
public async Task PayAsync_WhenDeclined_NeverCaptures()
{
var gateway = new Mock<IPaymentGateway>();

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

var sut = new CheckoutService(
gateway.Object, Mock.Of<ICouponRepository>(),
new FakeTimeProvider(Now), NullLogger<CheckoutService>.Instance);

await sut.PayAsync(Money.Try(500m), couponCode: null);

gateway.Verify(
x => x.CaptureAsync(It.IsAny<string>(), It.IsAny<Money>(), It.IsAny<CancellationToken>()),
Times.Never);
}

Here every argument is It.IsAny. That is deliberate. With Times.Never, wide matchers make the check stronger: no capture of any kind is allowed. A narrow matcher such as "AUTH-77" would let a capture with a different reference slip through.

Mock.Of<ICouponRepository>() creates a one-line double for a dependency the test does not care about. The decline reason "Kart bloke" means "card blocked".

Performance Contracts and VerifyNoOtherCalls

Sometimes "did not call" protects performance. When no coupon code is given, the service should not touch the database.

M05.TestableDesign.Tests/MoqVerifyTests.cs

[Fact]
public async Task PayAsync_WithoutCouponCode_NeverQueriesCouponRepository()
{
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-1"));

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

await sut.PayAsync(Money.Try(500m), couponCode: null);

// An unnecessary database round trip is a PERFORMANCE contract; verifying it is legitimate.
coupons.Verify(
x => x.FindAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
Times.Never);

// VerifyNoOtherCalls says "nothing else was called". Strong but FRAGILE;
// use it only when the whole boundary is the contract.
coupons.VerifyNoOtherCalls();
}

VerifyNoOtherCalls() fails if the mock received any call that was not already verified. On a repository with one method it adds little risk. On a gateway with several methods it freezes the exact set of calls, and any harmless new call breaks the test. Use it only when the whole interaction with that boundary is the contract.

Verifying the Argument That Matters

The last test checks that the repository is queried with exactly the code the customer entered.

M05.TestableDesign.Tests/MoqVerifyTests.cs

[Fact]
public async Task PayAsync_WithCoupon_QueriesRepositoryWithExactCode()
{
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

coupons
.Setup(x => x.FindAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Coupons.HalfPrice());

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Approve("AUTH-50"));

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

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

result.Charged.Amount.Should().Be(500m);
coupons.Verify(x => x.FindAsync("YARIYIL50", It.IsAny<CancellationToken>()), Times.Once);
}

The setup is wide (It.IsAny<string>()) and the verification is narrow ("YARIYIL50"). This split gives a better failure message. If the service passed a wrong code, a narrow setup would just return null and the test would fail on the amount, far from the cause. Here the setup still answers, and Verify reports exactly which code was used. The outcome assertion on Charged.Amount comes first because the result is what the user sees.

A common mistake is to verify a call whose effect the test already proves. If the gateway returned an approval and the result is successful, AuthorizeAsync was obviously called; verifying it adds coupling and no protection. Verify only effects that leave no other observable trace, such as the capture.

Summary

  1. Verify(expression, Times.X) checks how many matching calls a mock received; failures list the actual calls.
  2. Verify interactions that are part of the contract, such as "capture exactly once", not every internal step.
  3. With Times.Never, use wide matchers so no call of any kind can slip through.
  4. A wide setup plus a narrow Verify gives clearer failures than a narrow setup alone.
  5. VerifyNoOtherCalls() freezes the full set of calls; use it only when that whole set is the contract.