Nunit async test exception assertion

后端 未结 6 1698
感情败类
感情败类 2020-12-29 18:37

[Edit (May 2020)] - This issue has been reportedly addressed in newer releases of NUnit. Please see Nunit.ThrowsAsync. (Ref this answer, thanks @James-Ross)

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 19:05

    You're seeing problems due to async void.

    In particular:

    1. async () => await userController.Get("foo") is converted into TestDelegate, which returns void, so your lambda expression is treated as async void. So the test runner will begin executing the lambda but not wait for it to complete. The lambda returns before Get completes (because it's async), and the test runner sees that it returned without an exception.

    2. Wait wraps any exceptions in an AggregateException.

    3. Again, the async lambda is being treated as async void, so the test runner is not waiting for its completion.

    4. I recommend you make this async Task rather than async void, but in this case the test runner does wait for completion, and thus sees the exception.

    According to this bug report, there is a fix for this coming in the next build of NUnit. In the meantime, you can build your own ThrowsAsync method; an example for xUnit is here.

提交回复
热议问题