unit testing asynchronous operation

前端 未结 4 564
名媛妹妹
名媛妹妹 2021-02-13 11:41

I want to unit test a method that I have that performs and async operation:

 Task.Factory.StartNew(() =>
        {
            // method to test and return v         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 12:39

    I would propose to stub a TaskScheduler in your method with a special implementation for unit tests. You need to prepare your code to use an injected TaskScheduler:

     private TaskScheduler taskScheduler;
    
     public void OperationAsync()
     {
         Task.Factory.StartNew(
             LongRunningOperation,
             new CancellationToken(),
             TaskCreationOptions.None, 
             taskScheduler);
     }
    

    In your unit test you can use the DeterministicTaskScheduler described in this blog post to run the new task on the current thread. Your 'async' operation will be finished before you hit your first assert statement:

    [Test]
    public void ShouldExecuteLongRunningOperation()
    {
        // Arrange: Inject task scheduler into class under test.
        DeterministicTaskScheduler taskScheduler = new DeterministicTaskScheduler();
        MyClass mc = new MyClass(taskScheduler);
    
        // Act: Let async operation create new task
        mc.OperationAsync();
        // Act:  Execute task on the current thread.
        taskScheduler.RunTasksUntilIdle();
    
        // Assert
        ...
    }
    

提交回复
热议问题