Search code examples
c#unit-testingtask-parallel-librarycancellationtokensource

Why does this test keeps failing?


The test is as follows:

[TestMethod()]
public void IncrementTestNegative() {

    CancellationTokenSource s = new CancellationTokenSource();
    s.CancelAfter(10);

    ManualResetEventSlim evt = new ManualResetEventSlim();

    bool breached = false;
    Task.Run(() => {
        Thread.Sleep(200);
        breached = true;
    }, s.Token).ContinueWith((t) => {
        evt.Set();
    });


    evt.Wait();
    Assert.IsFalse(breached);
}

If I provide a value of "0" to CancelAfter, then the test case succeeds. Why does this test keep failing with other values.

This is using MS Test framework within Visual Studio Express


Solution

  • Cancelling the token does not abort the task. It merely sets the flag which you have to check for inside the task (CancellationToken.IsCancellationRequested). However, if the token is cancelled before the Task even starts, the Task will not run and will skip to the continuation.

    The fact that you expect breached to be false after the tests implies that you expected the task to be aborted after the period specified with CancelAfter.

    In other words, your Thread.Sleep(200) does not have a purpose, although the token will probably be cancelled at ~10ms after the task starts (you shouldn't expect very precise timing).