We have been using xUnit Framework in our project as test framework since the begining. Currently there are 2200+ unit tests in project and everything seems fine.
Bu
The problem is that async void
method does not return a Task
object which xUnit could possibly examine for exceptions. xUnit cannot even track the completion of a particular async void
method, as opposed to an async Task
method.
Moreover, async void
methods do not throw exceptions on the same stack frame, even for exceptions thrown from the synchronous part of the method. Rather, exceptions are propagated to the current synchronization context via SynchronizationContext.Post
(in case SynchronizationContext.Current != null
), or otherwise via ThreadPool.QueueUserWorkItem
. This behavior is different from async Task
methods, more details. It's possible to track the total number of the pending async void
methods (via SynchronizationContext.OperationStarted
/OperationCompleted
), but not individual methods.
So, changing the XunitTestMethod_Async
method's signature from async void
to async Task
should solve the problem.
Updated, it's 2019 and as @maracuja-juice points out, both asynv void
tests now fail, as they original should have behaved. xUnit team has implemented AsyncTestSyncContext, their special flavor of synchronization context, an instance of which they install to individually track each async void
call and capture any exceptions.