unit testing asynchronous operation

前端 未结 4 563
名媛妹妹
名媛妹妹 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:36

    Set UI and background task schedulars and replace them in unit test with this one.

    Below code was copied from internet, sorry for missing reference to author:

      public class CurrentThreadTaskScheduler : TaskScheduler
      {
        protected override void QueueTask(Task task)
        {
          TryExecuteTask(task);
        }
    
        protected override bool TryExecuteTaskInline(
           Task task,
           bool taskWasPreviouslyQueued)
        {
          return TryExecuteTask(task);
        }
    
        protected override IEnumerable GetScheduledTasks()
        {
          return Enumerable.Empty();
        }
    
        public override int MaximumConcurrencyLevel => 1;
      }
    

    So to test code:

       public TaskScheduler TaskScheduler
        {
          get { return taskScheduler ?? (taskScheduler = TaskScheduler.Current); }
          set { taskScheduler = value; }
        }
    
        public TaskScheduler TaskSchedulerUI
        {
          get { return taskSchedulerUI ?? (taskSchedulerUI = TaskScheduler.FromCurrentSynchronizationContext()); }
          set { taskSchedulerUI = value; }
        }
      public Task Update()
        {
          IsBusy = true;
          return Task.Factory.StartNew( () =>
                     {
                       LongRunningTask( );
                     }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler )
                     .ContinueWith( t => IsBusy = false, TaskSchedulerUI );
        }
    

    You will write following unit test:

    [Test]
    public void WhenUpdateThenAttributeManagerUpdateShouldBeCalled()
    {
      taskScheduler = new CurrentThreadTaskScheduler();
      viewModel.TaskScheduler = taskScheduler;
      viewModel.TaskSchedulerUI = taskScheduler;
      viewModel.Update();
      dataManagerMock.Verify( s => s.UpdateData( It.IsAny>() ) );
    }
    

提交回复
热议问题