Modern unit tests frameworks support awaiting the results of an asychronous unit test, like this:
public async Task SomeTest()
{
var result = await SomeMethodAsync();
// ... Verify the result ...
}
Is there any advantage of using this async approach over simply blocking?
public void SomeTest()
{
var result = SomeMethodAsync().Result;
// ... Verify the result ...
}
Does the async only provide a benefit when running tests in parallel?
The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.
Moreover, support for async void unit tests varies across frameworks, and even framework versions. For these reasons, it's best to avoid async void unit tests.
Async/Await makes it easier to write promises. The keyword 'async' before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.
Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.
The primary benefits of async
code are a responsive UI on the client side, and scalability on the server side. For unit tests, you get a bit of scalability (which translates to overall speed benefits since unit tests are bursted by nature).
But it's not a huge benefit. Your tests would (probably) run a bit faster.
I usually use async Task
unit test methods for these reasons:
await
doesn't wrap exceptions in AggregateException
.async Task
unit tests methods have been supported by every major unit test framework since 2012.Is there any advantage of using this async approach over simply blocking?
I think that really depends on what you're testing. If you look at it from the unit test frameworks point of view, then I don't see any benefit here. I don't think such a framework needs to scale with respect to IO. The only thing that you are doing is testing how your async API's behave. For example, as a library author, you could have an async endpoint and test what happens when your code is synchronously blocked by a caller which doesn't understand how to consume your library properly.
One example could be:
[TestClass]
public class M
{
[TestMethod]
public void X()
{
var myService = new MyService();
myService.FetchSomeDataAsync().Result; // Will this deadlock?
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With