skip to content

In xunit.v3, what does TestContext.Current expose, and why should async tests pass TestContext.Current.CancellationToken to the code they call?

level: middleimportance: should knowfreq 42%

answer

  1. ambient context, flows with async calls
  2. Test, TestState, TestOutputHelper
  3. AddAttachment, AddWarning, SendDiagnosticMessage
  4. token cancelled on timeout or aborted run
  5. ITestContextAccessor for injection

basics

~20 s

TestContext.Current is xunit.v3's ambient view of the running test: identity, state, output, attachments, warnings and a CancellationToken. Passing that token into async calls lets a timed-out or aborted test stop instead of running on in the background.

solid answer

~40 s

`TestContext.Current` returns an `ITestContext` for whatever is executing, held in an `AsyncLocal` so it flows through `await`. It exposes the current `Test`, `TestCase`, `TestMethod` and `TestClass`, the `TestState` after the test has run, the `PipelineStage`, the per-test `TestOutputHelper`, `AddAttachment(...)` and `AddWarning(...)`, `SendDiagnosticMessage(...)`, a `KeyValueStorage` for extensions, and `CancellationToken`. That token is signalled when the run is being aborted and when a test exceeds its `Timeout`: the runner fails the test with "Test execution timed out after N milliseconds" and calls `CancelCurrentTest()`. If the ticketing client's `HoldSeatAsync(seat, ct)` received the token, the work stops; if not, it keeps running after the test has been reported, competing with later tests. Constructors and fixtures can take `ITestContextAccessor` instead of using the static property.

code

csharp · 17 lines
csharp
public class SeatHoldTests
{
    [Fact(Timeout = 5_000)]
    public async Task Hold_expires_after_the_grace_period()
    {
        var ct = TestContext.Current.CancellationToken;
        var client = TicketingClientFactory.ForSandbox();

        var hold = await client.HoldSeatAsync("A12", ct);
        await Task.Delay(hold.GracePeriod + TimeSpan.FromMilliseconds(200), ct);

        var status = await client.GetHoldAsync(hold.Id, ct);
        TestContext.Current.AddAttachment("hold.json", status.RawJson);

        Assert.Equal(HoldState.Expired, status.State);
    }
}

go deeper

for a junior

Know that TestContext.Current gives access to the running test and its CancellationToken, and pass that token to async calls.

for a middle

Explain what the context exposes, that it flows through await via AsyncLocal, and how timeouts signal the token through CancelCurrentTest.

for a senior

Prevent runaway tests: thread the token through every cancellable call, attach evidence to failures, and inject ITestContextAccessor where statics are awkward.

for a principal

Make cancellation and diagnostic attachments a suite-wide convention so CI timeouts end cleanly and failures carry their own evidence.

## An ambient context for the running test In xUnit.net v2, code inside a test had no built-in way to ask "which test am I in?", and anything a helper needed had to be passed in through the constructor. xunit.v3 adds `TestContext.Current`, a static property returning `ITestContext`. It is stored in an `AsyncLocal`, so it follows the logical flow of the test through `await` calls and into helpers, while parallel tests each see their own context. ## What it exposes | Member | Use | |---|---| | `Test`, `TestCase`, `TestMethod`, `TestClass` | identity of what is running, for example for naming temporary resources | | `TestState`, `TestStatus`, `PipelineStage` | where the pipeline is and, after the test, its result | | `TestOutputHelper` | the current test's output helper, reachable from helpers | | `AddAttachment(...)` | attach text or binary data, such as a captured ticket PDF, to the result | | `AddWarning(...)` | record a warning on a test that still passes | | `SendDiagnosticMessage(...)` | runner-level diagnostics | | `KeyValueStorage` | a dictionary for extensions to pass data between pipeline stages | | `CancelCurrentTest()` | signal the token from inside | | `CancellationToken` | the cancellation signal described below | Outside a running test, some members are `null`; for example, `Test` is `null` at pipeline stages before any test starts, such as class fixture creation, and `TestState` is only filled in after the test has finished. ## Why the cancellation token matters The token is signalled in two situations: 1. **The run is being aborted**, for example when the user cancels, so in-flight work can stop quickly. 2. **The test exceeded its `Timeout`.** When `[Fact(Timeout = 5000)]` is exceeded, the runner records a failure with "Test execution timed out after 5000 milliseconds" and then calls `CancelCurrentTest()`, which signals the token. The second case is the one that bites. The runner stops **waiting** for a timed-out test, but it cannot stop code that ignores cancellation. A `HoldSeatAsync` call against a slow ticketing API that was not given the token keeps running after the test has been reported as failed: it holds threads and connections, it may write to shared state while later tests run, and its exceptions surface in unrelated places. Passing `TestContext.Current.CancellationToken` into every cancellable call lets the work end when the test does: ```csharp var hold = await client.HoldSeatAsync("A12", TestContext.Current.CancellationToken); ``` The same applies to `Task.Delay`, `HttpClient` calls, database commands and channel reads inside tests. ## Timeouts and the debugger - `Timeout` is in milliseconds and applies to the test method; `0`, the default, means no limit. - While a debugger is attached, xunit.v3 does not apply timeouts at all, so stepping through a slow hold request does not fail the test halfway. - xUnit.net documents timeouts as reliable only with the conservative parallel algorithm or with parallelism off, because the aggressive algorithm can delay a started test behind others. ## Getting the context without the static For code that prefers constructor injection, xunit.v3 supplies `ITestContextAccessor`, whose `Current` property returns the same context. Test class constructors and fixture constructors can both declare it, which is useful in fixtures that outlive a single test and need to look up the current test when called. ## Practical uses beyond cancellation - **Attachments for failures.** Save the reservation request and response bodies with `AddAttachment` so a CI failure carries its evidence. - **Warnings.** Use `AddWarning` for a degraded but acceptable condition, such as a fallback pricing source; the `failWarns` option can turn those into failures in strict pipelines. - **Helpers that log.** A shared `TicketingApiHelper` can write to `TestContext.Current.TestOutputHelper` without every test passing an output helper in. - **Unique names.** Derive temporary queue or file names from the test's identity so parallel tests never collide. ## Limits - The context is per test flow; a background task started with no link to the test, or one that outlives it, should not rely on it. - `KeyValueStorage` is meant for extension authors; tests rarely need it. - The token is a request to stop; the code under test has to observe it for anything to happen.

  • What happens to a timed-out test whose code ignores the cancellation token?
    The runner reports the failure ("Test execution timed out after N milliseconds") and moves on, but the test's task keeps running in the background. It can hold connections, mutate shared state while later tests run and raise exceptions that show up elsewhere. Passing `TestContext.Current.CancellationToken` lets the cancellable calls end as soon as the runner calls `CancelCurrentTest()`.
  • How does a fixture reach the current test's context?
    Declare an `ITestContextAccessor` constructor parameter on the fixture and read `accessor.Current` when a test calls into it. The accessor returns the context of whatever is running at that moment, which a fixture created once for many tests cannot capture in its constructor.

  • TestContext.Current exists in xUnit.net v2 under the Xunit.Abstractions namespace.
  • When a test times out, xunit.v3 forcibly aborts the code it was running.
  • The test's CancellationToken is only signalled when the user presses Ctrl+C.
  • TestContext.Current is a single shared object, so parallel tests overwrite each other's context.
  • Fixtures cannot reach the test context because they are created before tests.

Assumes xunit.v3 4.x: TestContext.Current, ITestContextAccessor and the per-test CancellationToken do not exist in xUnit.net v2.