Lesson 42 of 93 · 5 min read · Updated

Mocking Async Methods in Moq: Cancellation Tokens and TaskCompletionSource

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

  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

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

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);

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

[Fact]
public async Task PayAsync_PropagatesCancellationTokenToTheBoundary()
{
var gateway = new Mock<IPaymentGateway>();
using var cts = new CancellationTokenSource();

gateway
// We check that the SAME token is passed: cancellation behavior is a contract.
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), cts.Token))
.ReturnsAsync(Authorization.Approve("AUTH-CT"));

var sut = CreateSut(gateway.Object);

var result = await sut.PayAsync(Money.Try(100m), null, cts.Token);

result.IsSuccessful.Should().BeTrue();
gateway.Verify(x => x.CaptureAsync("AUTH-CT", It.IsAny<Money>(), cts.Token), Times.Once);
}

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:

  1. If AuthorizeAsync received a different token, the setup would not match, the loose mock would return a null authorization, and the test would fail.
  2. If CaptureAsync received a different token, the Verify with cts.Token would 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

[Fact]
public async Task PayAsync_WithTaskCompletionSource_LetsTheTestControlTiming()
{
// TaskCompletionSource: the TEST decides "when does the answer arrive?".
// Use it only when TIMING is part of the scenario (race conditions, timeouts...).
var tcs = new TaskCompletionSource<Authorization>();
var gateway = new Mock<IPaymentGateway>();

gateway
.Setup(x => x.AuthorizeAsync(It.IsAny<Money>(), It.IsAny<CancellationToken>()))
.Returns(tcs.Task);

var sut = CreateSut(gateway.Object);

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

pending.IsCompleted.Should().BeFalse("ağ geçidi henüz yanıt vermedi");

// Now we provide the answer ourselves.
tcs.SetResult(Authorization.Approve("AUTH-TCS"));

var result = await pending;
result.Reference.Should().Be("AUTH-TCS");
}

Step by step:

  1. The setup uses Returns(tcs.Task), not ReturnsAsync. The mock hands out the pending task.
  2. The test calls PayAsync without awaiting it. The service runs until it awaits the gateway, then returns its own pending task.
  3. pending.IsCompleted.Should().BeFalse(...) proves the service is really waiting. The reason text means "the gateway has not answered yet".
  4. tcs.SetResult(...) completes the gateway task. The service continues, captures the payment and finishes.
  5. 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

[Fact]
public void MockOf_CreatesQuickStubsForUninterestingDependencies()
{
// Mock.Of<T>(): a one-line "I do not care" double.
// It is Moq's version of a DUMMY.
ICouponRepository dummy = Mock.Of<ICouponRepository>();

dummy.Should().NotBeNull();
}

Summary

  1. ReturnsAsync returns an already-completed task; it is the right default when timing does not matter.
  2. Match the exact CancellationToken in a setup or Verify to prove the service passes it to the boundary.
  3. Returns(tcs.Task) with a TaskCompletionSource<T> lets the test decide when the dependency answers.
  4. Use the pending-task technique only for timing scenarios such as timeouts, cancellation and races, and always complete the source.
  5. Mock.Of<T>() gives a one-line dummy for dependencies the test does not use.