[ACCEPTED]-xUnit Async Test Not Working Properly-xunit

Accepted answer
Score: 39

The problem is that async void method does not return 21 a Task object which xUnit could possibly examine 20 for exceptions. xUnit cannot even track 19 the completion of a particular async void method, as 18 opposed to an async Task method.

Moreover, async void methods 17 do not throw exceptions on the same stack 16 frame, even for exceptions thrown from the 15 synchronous part of the method. Rather, exceptions 14 are propagated to the current synchronization 13 context via SynchronizationContext.Post (in case SynchronizationContext.Current != null), or otherwise via 12 ThreadPool.QueueUserWorkItem. This behavior is different from async Task methods, more details. It's 11 possible to track the total number of the 10 pending async void methods (via SynchronizationContext.OperationStarted/OperationCompleted), but not individual 9 methods.

So, changing the XunitTestMethod_Async method's signature 8 from async void to async Task should solve the problem.

Updated, it's 7 2019 and as @maracuja-juice points out, both 6 async void tests now fail, as they original should 5 have behaved. xUnit team has implemented 4 AsyncTestSyncContext, their special flavor of synchronization 3 context, an instance of which they use to 2 individually track each async void call and capture 1 any exceptions.

More Related questions