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

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

    Bear in mind that the NUnit 2.6 series, like those before it, is built to target the .NET 2.0 framework. So, NUnit can only do the same things you could code yourself, in an assembly targeting .NET 2.0.

    Specifically, you can't mark your test method as async and expect NUnit to do anything special with it.

    You can, however,

    • Target .NET 4.5 for your tests. NUnit will run them in a separate process.
    • Use await in your test to wait for the result of a call to an async method.

    Neither of the above will give you asynchronous test execution, if that's what you are hoping for. No other tests will execute while waiting for the asynchronous operation to complete.

    Another option is to use NUnitLite. NUnitLite 0.8 supports the [Asynchronous] attribute which will allow other tests to continue while your asynchronous test completes. The advantage of the attribute is that it allows asynchronous tests to work in .NET 2.0 through 4.0

    We don't currently have a .NET 4.5 build of NUnitLite but it will be added soon and we are working on a change that will make use of [Asynchronous] optional in that environment. For now, you can easily download and recompile the source code for .NET 4.5.

    For the future, look to NUnit 3.0 to support async methods fully along with general parallel execution of tests on multiple threads or in multiple processes.

提交回复
热议问题