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

后端 未结 5 1108
余生分开走
余生分开走 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:07

    As of today (7/2/2014) async testing is supported by:

    • xUnit: with async methods that return a Task (since 1.9)
    • MSTest: with async methods that return a Task (since VS 2012)
    • NUnit: with async methods that return a Task, or even, that return void, since 2.6.2

    In the first two frameworks, the test method must have this signature:

    [TestMethod]
    public async Task MyTestMethod()
    {
       ...
       var result = await objectUnderTest.TestedAsyncMethod(...);
       // Make assertions
    }
    

    NUnit, apart from that signature, supports this one:

    public async void MyTestMethod()
    

    Of course, inside any of these test methods you can use await to call and wait on asynchronous methods.

    If you're using a testing framework that doesn't support async test methods, then, the only way to do it, is to call the async method and wait until it finishes running using any of the usual ways: await, reading the Result property of the Task returned by an async method, using any of the usual wait methods of Task and so on. After the awaiting, you can do all the asserts as usual. For example, using MSTest:

    [TestMethod]
    public void MyTestMethod()
    {
        ...
        Task task = objectUnderTest.MyAsyncMethod(...);
        // Make anything that waits for the method to end
        MyResultClass result = task.Result;
    
        // Make the assertions
        Assert.IsNotNull(result);
        ...
    }
    

提交回复
热议问题