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.
xUnit.net v3 now provides support for CancellationToken
in tests. It can be accessed in two ways:
- The static
TestContext.Current.CancellationToken
- 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);
}
}
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.