Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Property | Value |
---|---|
Rule ID | MSTEST0045 |
Title | Use cooperative cancellation for timeout |
Category | Design |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default | Yes |
Default severity | Info |
Introduced in version | 3.10.0 |
Is there a code fix | Yes |
Cause
A test method uses TimeoutAttribute without setting the CooperativeCancellation
property to true
.
Rule description
There's no way to gracefully abort a running thread. There are two ways for a timeout to work:
- Stop observing the thread running the test. But this can be problematic in many cases and might make the remaining tests unstable due to potential race conditions. This is non-cooperative cancellation.
- Request cancellation once the timeout is reached, and it's the test responsibility to terminate on request. This is cooperative cancellation.
When using TimeoutAttribute, you should set CooperativeCancellation
to true
to enable cooperative cancellation. Without cooperative cancellation, the test framework stops observing the test execution when the timeout is reached, but the test continues running in the background. This can lead to problems for other tests or cleanup steps, as the original test is still executing and might interfere with subsequent operations.
When using cooperative cancellation mode, MSTest only triggers cancellation of the token and you're responsible for flowing and utilizing the test context token in your test code. This mode aligns with the default behavior of cancellation in .NET.
How to fix violations
Use the provided code fixer to automatically set the CooperativeCancellation
property to true
on the TimeoutAttribute. You can also manually add the property if needed.
[TestClass]
public class TestClass1
{
public TestContext TestContext { get; set; }
[Timeout(TimeoutValue, CooperativeCancellation = true)]
[TestMethod]
public void TestMethod1()
{
// Respect TestContext.CancellationTokenSource.Token
}
}
Alternatively, you can configure cooperative cancellation globally in your runsettings or testconfig.json file to apply this setting to all timeout attributes in your test project.
When to suppress warnings
Suppress this warning if you specifically need the test to be terminated abruptly when the timeout is reached, rather than using cooperative cancellation.