Why do I need async support for MS Unit Test if Task.Result can be used?

I am a little puzzled here ... I have a testing method that calls the async method call, and I changed the signature to async Task . Works.

 [TestMethod] public async Task TestIt() { bool result = await service.SomethingAsync(); Assert(result); } 

Now I read across the Internet that asynchronization support is required in unit tests and is now also in NUnit. But why is this so important? I can write the test as follows, using the Result property, which will wait for the Task to complete:

 [TestMethod] public void TestIt() { bool result = service.SomethingAsync().Result; Assert(result); } 
+6
source share
1 answer

Result has the unfortunate side effect of wrapping all exceptions in an AggregateException . This makes testing the error path more painful.

But even if you decide that you can live with it, you still have the problem of calling multiple async methods in the same test; those. if your test setup also requires async work. To do this in a blocking way, you will either have to reorganize your test method into a separate async method, or wrap it in an async delegate and either execute it directly, or transfer it to Task.Run . Not impossible, but not convenient.

Finally, there is a problem with async components that take a single thread context at a time. Examples include ViewModels and WebAPI / MVC controllers. At this level, these components often assume that they do not need to synchronize access to asynchronous shared data, since they are never executed in the context of an arbitrary thread. Before you unit test, that is. The general approach is to give these unit tests a single-threaded context, for example, to install Dispatcher in the unit test stream. In this case, a Result will be inhibited. There are ways around this, but again, it is not convenient to write this code.

The bottom line is that async unit tests do not allow; they make it convenient. And anything that encourages unit testing (especially for more complex things like async ) is a good idea. :)

+3
source

All Articles