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

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

    It really depends on what they're doing. Usually they'll be depending on something else which provides a Task or something similar. In that case, you may be able to provide fake dependencies which allow you to control all of this in a fine-grained way. I've got a prototype "time machine" which allows you to preprogram tasks to complete at particular artificial times, then move time forward and perform assertions as you go. There's a blog post about it which you may find useful. As I say, it's only a prototype and it's not appropriate for all scenarios - but it may suit you.

    Stephen Cleary also has a couple of blog posts around unit testing (1, 2), taking a slightly different approach, along with a NuGet package you may find useful.

    The basic approach is the same as normal though: give your method different inputs (and dependency outputs) and test the results. It's definitely trickier achieving that with asynchrony, but it's doable.

提交回复
热议问题