Lesson 42 of 93 · 5 min read · Updated
Mocking Async Methods in Moq: Cancellation Tokens and TaskCompletionSource
On this page
Most boundaries in modern .NET code are asynchronous. ReturnsAsync makes an async mock easy to set up, but it always returns a task that is already complete. That hides two things a test sometimes needs to see: whether the CancellationToken really reaches the boundary, and what the code does while it is still waiting for an answer. This lesson shows how to verify token propagation and how to use TaskCompletionSource to let the test decide when a response arrives.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- Microsoft.Extensions.TimeProvider.Testing 11.0.0
What ReturnsAsync Does
ReturnsAsync(value) is shorthand for Returns(Task.FromResult(value)). The task is complete before the service even awaits it, so the await continues synchronously. For most tests that is what you want: the test is fast and the scenario is about the value, not the timing.
The tests in this lesson share a factory that fills the dependencies they do not care about.
M05.TestableDesign.Tests/MoqAdvancedTests.cs
The Cancellation Token Is a Contract
CheckoutService.PayAsync accepts a CancellationToken and must pass it to every boundary call. If it passes CancellationToken.None or default instead, a request that the user cancels keeps running against the payment provider. Nothing in the return value shows this bug, so the test must look at the arguments.
Most setups use It.IsAny<CancellationToken>() because the token does not matter to them. This test does the opposite and matches the exact token.
M05.TestableDesign.Tests/MoqAdvancedTests.cs
CancellationToken is a struct, and two tokens are equal when they come from the same CancellationTokenSource. So cts.Token in the setup matches only the token the test passed in. The test checks both boundary calls:
- If
AuthorizeAsyncreceived a different token, the setup would not match, the loose mock would return anullauthorization, and the test would fail. - If
CaptureAsyncreceived a different token, theVerifywithcts.Tokenwould fail with a clear message.
using var cts disposes the source at the end of the test. Disposing is good practice even in tests, because a CancellationTokenSource can hold a timer.
Letting the Test Control Timing
Sometimes the timing is the scenario. What does the service do while the gateway has not answered yet? Does a timeout fire? Do two concurrent requests interfere? A completed task cannot answer those questions. TaskCompletionSource<T> gives the test a task that stays pending until the test completes it.
M05.TestableDesign.Tests/MoqAdvancedTests.cs
Step by step:
- The setup uses
Returns(tcs.Task), notReturnsAsync. The mock hands out the pending task. - The test calls
PayAsyncwithout awaiting it. The service runs until it awaits the gateway, then returns its own pending task. pending.IsCompleted.Should().BeFalse(...)proves the service is really waiting. The reason text means "the gateway has not answered yet".tcs.SetResult(...)completes the gateway task. The service continues, captures the payment and finishes.- The test awaits the service task and checks the result.
Between steps 2 and 4 the test could do other things: cancel the token, start a second request, or advance a FakeTimeProvider to trigger a timeout. That is how you test concurrency and timeout logic without Task.Delay and without flaky timing.
Pitfall: Do Not Use It When Timing Is Not the Point
TaskCompletionSource adds steps and makes a test harder to read. If the scenario is "an approved payment returns success", ReturnsAsync says it in one line. Use the pending-task technique only when the behavior under test depends on the order of events in time.
Two more details matter when you do use it. First, a test that forgets to call SetResult will hang on await pending forever, so always complete the source on every path. Second, by default the code after SetResult may run continuations inline on the test's thread. In production code that completes a TaskCompletionSource, consider TaskCreationOptions.RunContinuationsAsynchronously to avoid surprising re-entrancy.
Quick Dummies with Mock.Of
The factory above uses Mock.Of<ICouponRepository>(). It returns the object directly, with no Mock<T> wrapper, and behaves like a loose mock. It is the shortest way to satisfy a constructor parameter that the test does not use: a dummy.
M05.TestableDesign.Tests/MoqAdvancedTests.cs
Summary
ReturnsAsyncreturns an already-completed task; it is the right default when timing does not matter.- Match the exact
CancellationTokenin a setup orVerifyto prove the service passes it to the boundary. Returns(tcs.Task)with aTaskCompletionSource<T>lets the test decide when the dependency answers.- Use the pending-task technique only for timing scenarios such as timeouts, cancellation and races, and always complete the source.
Mock.Of<T>()gives a one-line dummy for dependencies the test does not use.