Building unit tests for MVC2 AsyncControllers

后端 未结 2 829
无人及你
无人及你 2021-02-20 16:24

I\'m considering re-rewriting some of my MVC controllers to be async controllers. I have working unit tests for these controllers, but I\'m trying to understand how to maintain

2条回答
  •  旧时难觅i
    2021-02-20 16:47

    As with any async code, unit testing needs to be aware of thread signalling. .NET includes a type called AutoResetEvent which can block the test thread until an async operation has been completed:

    public class MyAsyncController : Controller
    {
      public void TransactionAsync()
      {
        AsyncManager.Parameters["result"] = "result";
      }
    
      public ContentResult TransactionCompleted(string result)
      {
        return Content(result);
      }
    }
    
    [TestFixture]
    public class MyAsyncControllerTests
    {
      #region Fields
      private AutoResetEvent trigger;
      private MyAsyncController controller;
      #endregion
    
      #region Tests
      [Test]
      public void TestTransactionAsync()
      {
        controller = new MyAsyncController();
        trigger = new AutoResetEvent(false);
    
        // When the async manager has finished processing an async operation, trigger our AutoResetEvent to proceed.
        controller.AsyncManager.Finished += (sender, ev) => trigger.Set();
    
        controller.TransactionAsync();
        trigger.WaitOne()
    
        // Continue with asserts
      }
      #endregion
    }
    

    Hope that helps :)

提交回复
热议问题