title: Simulating CancellationToken.IsCancellationRequested when unit testing
body: <p>I would like to test a task that is supposed to run continuously until killed. Suppose the following method is being tested:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class Worker
  {
    public async Task Run(CancellationToken cancellationToken)
    {
      while (!cancellationToken.IsCancellationRequested)
      {
        try
        {
          // do something like claim a resource
        }
        catch (Exception e)
        {
          // catch exceptions and print to the log
        }
        finally
        {
          // release the resource
        }
      }
    }
  }
  </code></pre>
  
  <p>And a test case </p>
  
  <pre class="lang-cs prettyprint-override"><code>[TestCase]
  public async System.Threading.Tasks.Task Run_ShallAlwaysReleaseResources()
  {
    // Act
    await domainStateSerializationWorker.Run(new CancellationToken());  
  
    // Assert
    // assert that resource release has been called
  }
  </code></pre>
  
  <p>The problem is that the task never terminates, because cancellation is never requested. Ultimately I would like to create a <code>CancellationToken</code> stub like <code>MockRepository.GenerateStub&lt;CancellationToken&gt;()</code> and tell it on which call to <code>IsCancellationRequested</code> return <code>true</code>, but <code>CancellationToken</code> is not a reference type so it is not possible.</p>
  
  <p>So the question is how to make a test where <code>Run</code> executes for <code>n</code> iterations and then terminates? Is it possible without refactoring <code>Run</code>? </p>