Advantage of async / block waiting in unit tests

Modern unit tests support support for pending asynchronous unit test results, for example:

public async Task SomeTest() { var result = await SomeMethodAsync(); // ... Verify the result ... } 

Is there any advantage of using this asynchronous approach for simple blocking?

 public void SomeTest() { var result = SomeMethodAsync().Result; // ... Verify the result ... } 

Does asynchronous mode support only parallel test execution?

+5
source share
2 answers

The main benefits of async code are a flexible client-side user interface and server-side scalability. For unit tests, you get a little scalability (which is consistent with the overall speed benefits, since unit tests are torn by nature).

But this is not a huge benefit. Your tests (probably) will run faster.

I usually use async Task unit test methods for the following reasons:

  • If you are testing code inside the context, blocking can cause a classic deadlock problem. Please note that some frameworks (e.g. xUnit) always provide a default context. Even for other frameworks, it is often necessary to provide context for unit test ViewModels.
  • await does not wrap exceptions in an AggregateException .
  • You get a little scalability advantage, which (theoretically) allows your unit tests to run faster overall. Assuming your infrastructure runs your tests in parallel.
  • Why not? They are as simple as synchronous methods. async Task unit test methods are supported by all major unit test structures since 2012.
+6
source

Is there any advantage of using this asynchronous approach by simply blocking?

I think it really depends on what you are testing. If you look at it from the point of view of unit test frameworks, then I do not see any benefit here. I do not think that such a structure should scale in relation to IO. The only thing you do is check how your asynchronous API behaves. For example, as the author of a library, you can have an endpoint for asynchronous testing and check what happens when your code is synchronously blocked by a caller who does not understand how to use the library correctly.

One example would be:

 [TestClass] public class M { [TestMethod] public void X() { var myService = new MyService(); myService.FetchSomeDataAsync().Result; // Will this deadlock? } } 
+1
source

Source: https://habr.com/ru/post/1235006/


All Articles