Lesson 41 of 93 · 6 min read · Updated
Modeling Failures with Moq: ThrowsAsync, Callback and SetupSequence
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- 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
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
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
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
"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
ThrowsAsyncreturns a faulted task, which matches how real async dependencies fail.- Throw only exceptions the real boundary can throw, such as
HttpRequestExceptionfor an HTTP client. Callback<T1, T2>captures actual arguments so you can assert on them with normal, readable assertions.SetupSequencereturns answers in call order; use it only when order is part of the scenario, such as retries.- Each of these tools should describe something that can happen in production, not something that is merely easy to fake.