How do I test an async method with NUnit (or possibly with another framework)?

后端 未结 5 1110
余生分开走
余生分开走 2020-12-02 19:43

I have an ASP.NET Web API application, with an ApiController that features asynchronous methods, returning Task<> objects and marked with the async<

5条回答
  •  时光说笑
    2020-12-02 20:25

    I'm in the process of converting some of my methods to async. Getting this to work with NUnit has been quite straightforward.

    The test methods can not be asynchronous. But we still have access to the full functionality of the Task Parallel Library, we just can't use the await keyword directly in the test method.

    In my example, I had a method:

    public string SendUpdateRequestToPlayer(long playerId)
    

    And it was tested in NUnit like so:

    string result = mgr.SendUpdateRequestToPlayer(player.Id.Value);
    Assert.AreEqual("Status update request sent", result);
    mocks.VerifyAll();
    

    Now that I have altered the method SendUpdateRequestToPlayer to be asynchronous

    public async Task SendUpdateRequestToPlayer(long playerId)
    

    I simply had to modify my tests to Wait for the task to complete:

    Task task = mgr.SendUpdateRequestToPlayer(player.Id.Value);
    task.Wait(); // The task runs to completion on a background thread
    Assert.AreEqual("Status update request sent", task.Result);
    mocks.VerifyAll();
    

提交回复
热议问题