Featured image of post Handle cancellation in tests with xUnit.net v3

Handle cancellation in tests with xUnit.net v3

xUnit.net v3 finally brings native support for cancellation tokens in tests. Let's see how to use it.

Some tests may take a long time, and cancelling them in your IDE or CI might require some delay. File accesses, HTTP requests, database calls, delays, etc. can occur when you decide to interrupt the ongoing test run.

In some IDEs, like Rider, you can stop a test run, but the currently running tests will continue until they are finished. This is why the “Stop” button sometimes becomes “Terminate,” in order to kill the test process. On GitHub or Azure DevOps, terminating pipeline runs can also take some time. Repeatedly experiencing this can become frustrating.

Some long-running test that wont stop until completed or killed

xUnit.net v3 now provides support for CancellationToken in tests. It can be accessed in two ways:

  1. The static TestContext.Current.CancellationToken
  2. Via ITestContextAccessor injected in the test class’s constructor
public class UnitTest1(ITestContextAccessor testContextAccessor)
{
    [Fact]
    public async Task Test1()
    {
        await Task.Delay(30_000, TestContext.Current.CancellationToken);
    }
    
    [Fact]
    public async Task Test2()
    {
        await Task.Delay(30_000, testContextAccessor.Current.CancellationToken);
    }
}

The same test as before, but with cancellation support, stops immediately when requested

In retrospect, now that agent-mode LLMs can run tests, it makes sense to not only have them execute as quickly as possible, but also to ensure that if prompt responses are cancelled, they can halt immediately.

Licensed under CC BY 4.0
Ko-fi donations Buy me a coffee