Skip to content

Test fail when posting to SynchronizationContext.Current #3209

@glconti

Description

@glconti

Issue

Our code is relying on a third-party library which posts some action to be executed on the SynchronizationContext.Current, this breaks some tests that require Apartment(ApartmentState.STA) and return async Task.
We managed to strip down the problem to the following tests (one is failing while the other is not).

Tested with NUnit console 3.10.0 and NUnit framework 3.11.0

Failing test

[Test]
[Apartment(ApartmentState.STA)]
public async Task FailingTest()
{
    SynchronizationContext.Current.Post(state => { }, null);

    await Task.CompletedTask;
}

❗️ Exception

System.InvalidOperationException : Shutting down SingleThreadedTestSynchronizationContext with work still in the queue.
   in NUnit.Framework.Internal.SingleThreadedTestSynchronizationContext.ShutDown() in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\SingleThreadedSynchronizationContext.cs:riga 90
   in NUnit.Framework.Internal.AsyncToSyncAdapter.<>c__DisplayClass10_1.<InitializeExecutionEnvironment>b__0() in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\AsyncToSyncAdapter.cs:riga 128
   in NUnit.Framework.Internal.AsyncToSyncAdapter.Await(Func`1 invoke) in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\AsyncToSyncAdapter.cs:riga 88
   in NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context) in C:\src\nunit\nunit\src\NUnitFramework\framework\Internal\Commands\TestMethodCommand.cs:riga 84

Passing test

[Test]
[Apartment(ApartmentState.STA)]
public async Task SuccessfulTest()
{
    SynchronizationContext.Current.Post(state => { }, null);

    await Task.Yield();
}

Comments

We understood that Task.Yield() will force a context switch allowing for the synchronization context queue to be processed, while Task.Result won't. After having a look at the code and issues we saw that this is linked to #2818 and #2774

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions