Interview question
Test cancellation of a slow downstream call
Uses a controllable fake HTTP handler to prove request cancellation reaches a downstream dependency.
TL;DR
Uses a controllable fake HTTP handler to prove request cancellation reaches a downstream dependency.
Cancellation propagation, fake HttpMessageHandler, timeout boundaries, expected exceptions, and resource protection.
Practice the problem like a real interview: restate, reason, implement, and test.
Replace the pricing service handler with a test double that waits indefinitely until its cancellation token fires. Start the API request with a cancellable token, cancel it, and assert the downstream handler observed cancellation. No real network dependency is allowed.
The client aborts the request while pricing is pending. The fake handler records cancellation and no order is persisted.
Task.Delay timing guesses.I make the fake handler signal when it starts, then wait on its token. This removes timing races from the test. After cancellation I assert both propagation and absence of downstream business side effects.
[Fact]
public async Task Cancelled_request_cancels_pricing_call()
{
var handler = new BlockingPricingHandler();
await using var factory = new ApiTestFactory(services =>
services.AddHttpClient<IPricingClient, PricingClient>()
.ConfigurePrimaryHttpMessageHandler(() => handler));
var client = factory.CreateAuthenticatedClient("buyer-1", "quotes.create");
using var cancellation = new CancellationTokenSource();
var request = client.PostAsJsonAsync(
"/api/quotes",
new { ProductId = "p-1" },
cancellation.Token);
await handler.Started;
cancellation.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => request);
Assert.True(handler.CancellationObserved);
Assert.Equal(0, await factory.CountQuotesAsync());
}
The test exercises the real HTTP pipeline but replaces the external service and persistence with isolated dependencies. It proves cancellation wiring without sleeping or relying on a real timeout duration.
Next in Contracts & Reliability: Concurrency Integration Test