CancelAfter
Normally, NUnit simply runs tests and waits for them to terminate -- the test is allowed to run indefinitely. For certain kinds of tests, however, it may be desirable to specify a timeout value.
For .NET Core and later,
-Thread.Abort
as used by the
-TimeoutAttribue
can no longer be used, and there is therefore no way to interrupt an endless loop.
Thread.Abort
as used by the
+TimeoutAttribute
can no longer be used, and there is therefore no way to interrupt an endless loop.
For all tests, one could use the --blame-hang(-timeout)
options of dotnet test
. However, this will stop any further
execution of the remaining tests.
To still be able to cancel tests, one has to move to cooperative cancellation. See Cancellation in Managed Threads using a -`CancellationToken``.
+`CancellationToken``.The CancelAfterAttribute
is used to specify a timeout value in milliseconds for a test case. If the test case runs
longer than the time specified, the supplied CancellationToken
is set to canceled. It is however up to the test code
to check this token, either directly or indirectly.
Note
When debugging a unit test, i.e. when a debugger is attached to the process, the timeout is not enforced.