Lesson 41 of 93 · 6 min read · Updated

Modeling Failures with Moq: ThrowsAsync, Callback and SetupSequence

Happy paths are only half of a service's behavior. A payment provider can be unreachable, it can decline once and accept on retry, and the amount it receives is often the most important fact in a checkout. Moq has three tools for these cases: ThrowsAsync for error paths, Callback to capture arguments, and SetupSequence for answers that change from call to call. This lesson shows each one and the rule that keeps them honest: model only behavior the real boundary can produce.

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

A Small Factory for the Service

These tests only care about the payment gateway, so a helper fills the other dependencies with neutral values. Mock.Of<ICouponRepository>() gives a one-line double for the repository.

M05.TestableDesign.Tests/MoqAdvancedTests.cs

/// <summary>
/// Throws / ThrowsAsync -> error paths
/// Callback -> capture or inspect the argument that was passed
/// SetupSequence -> answers in order (use SPARINGLY!)
/// ReturnsAsync -> methods that return Task
/// TaskCompletionSource -> when timing is part of the scenario
///
/// WARNING: Model only behavior the REAL BOUNDARY can produce.
/// Can a real payment system "fail on the first call and succeed on the second"?
/// Yes (a transient error). So SetupSequence is legitimate here.
/// </summary>
public class MoqAdvancedTests
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

private static CheckoutService CreateSut(IPaymentGateway gateway, ICouponRepository? coupons = null) =>
new(gateway,
coupons ?? Mock.Of<ICouponRepository>(),
new FakeTimeProvider(Now),
NullLogger<CheckoutService>.Instance);

Error Paths with ThrowsAsync

When the payment provider cannot be reached, HttpClient throws HttpRequestException. A test can make the gateway double throw the same exception.

M05.TestableDesign.Tests/MoqAdvancedTests.cs

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

// ThrowsAsync: we model an error the boundary can really throw.
gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new HttpRequestException("Ödeme sağlayıcısına ulaşılamadı."));

var sut = CreateSut(gateway.Object);

var act = () => sut.PayAsync(Money.Try(100m), null);

// CheckoutService does NOT swallow this error; it passes it up. That is a
// deliberate design decision, and the test documents it.
await act.Should().ThrowAsync<HttpRequestException>();
}

ThrowsAsync returns a faulted task instead of throwing synchronously. This matters. Real async code fails when the task is awaited, and ThrowsAsync reproduces that. If you used Throws on an async method, the exception would be thrown at the moment of the call, before any await, which is not how a real client behaves.

The assertion uses FluentAssertions' ThrowAsync<T>() on a Func<Task>. The test does not catch the exception itself; it states that PayAsync lets it propagate. If someone later adds a catch that returns a failed result instead, this test fails and forces a conscious decision.

Pick exceptions the real dependency can throw. HttpRequestException and TaskCanceledException are realistic for an HTTP gateway. An OutOfMemoryException or a custom exception the real client never throws tests a scenario that cannot happen.

Capturing Arguments with Callback

Sometimes you want to assert on the argument a dependency received, and the condition is too complex for a readable It.Is expression. Callback runs your code each time the setup matches, with the actual arguments.

M05.TestableDesign.Tests/MoqAdvancedTests.cs

[Fact]
public async Task PayAsync_CallbackCapturesTheAuthorizedAmount()
{
var gateway = new Mock<IPaymentGateway>();
Money? captured = null;

// Callback: capture the argument, then write richer assertions AFTERWARDS.
// Often more readable than complex It.Is(...) expressions.
gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.Callback<Money, CancellationToken>((money, _) => captured = money)
.ReturnsAsync(Authorization.Approve("AUTH-CB"));

var sut = CreateSut(gateway.Object);

await sut.PayAsync(Money.Try(1_234.56m), null);

captured.Should().NotBeNull();
captured!.Value.Amount.Should().Be(1_234.56m);
captured.Value.Currency.Should().Be("TRY");
}

The generic arguments of Callback<Money, CancellationToken> must match the method's parameter types in order. If they do not, Moq rejects the callback with an ArgumentException ("Invalid callback").

Callback comes before ReturnsAsync in the chain. After the act step, the test has the real Money value and can use normal FluentAssertions on it. When an assertion fails, the message shows the actual amount and currency, which is clearer than the "no matching setup" style of failure you get from It.Is.

Use a callback for capture, not for behavior. If you find yourself writing if statements inside a callback, the double has become a hand-written fake in disguise. A small fake class is easier to read at that point.

Changing Answers with SetupSequence

SetupSequence returns a different result for each call, in order. Here the first authorization is declined with a transient error and the second is approved.

M05.TestableDesign.Tests/MoqAdvancedTests.cs

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

// SetupSequence: a different answer depending on the call ORDER.
gateway
.SetupSequence(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(Authorization.Decline("Geçici hata"))
.ReturnsAsync(Authorization.Approve("AUTH-RETRY"));

var sut = CreateSut(gateway.Object);

var first = await sut.PayAsync(Money.Try(100m), null);
var second = await sut.PayAsync(Money.Try(100m), null);

first.IsSuccessful.Should().BeFalse();
second.IsSuccessful.Should().BeTrue();

// NOTE: SetupSequence ties the test to call order. That moves the test closer
// to implementation details - use it only when the order is really part of the scenario.
}

"Geçici hata" means "transient error". A real gateway really can fail once and succeed a moment later, so this sequence describes something that happens in production. That is the test for whether a sequence is legitimate.

Pitfall: Use SetupSequence Sparingly

SetupSequence couples the test to the exact number and order of calls. If the service starts calling the gateway once more, for example to check a status, the answers shift by one and the test fails for a reason unrelated to the behavior. After the listed answers run out, further calls return the default value, which can hide bugs. Reach for it only when order is the point of the scenario, as in retry logic. For everything else, a single Setup with a stable answer is safer.

Summary

  1. ThrowsAsync returns a faulted task, which matches how real async dependencies fail.
  2. Throw only exceptions the real boundary can throw, such as HttpRequestException for an HTTP client.
  3. Callback<T1, T2> captures actual arguments so you can assert on them with normal, readable assertions.
  4. SetupSequence returns answers in call order; use it only when order is part of the scenario, such as retries.
  5. Each of these tools should describe something that can happen in production, not something that is merely easy to fake.