0

Why does this test fail?

[Test]
public async Task Test_Keeps_SynchronizationContext()
{
    SynchronizationContext.Current.Should().NotBeNull(); // OK
    await Task.Delay(1).ConfigureAwait(true);
    SynchronizationContext.Current.Should().NotBeNull(); // FAIL
}

(NUnit 3.13.3 on .NET 7.0)

2
  • Have you asked the NUnit team? Commented Jun 22, 2023 at 14:01
  • I read a few posts around NUnit and SynchronizationContexts (which did not match exactly) and I thought that maybe there is something I seem to overlook. But yes, I see this is pretty specific so I just created an issue on GitHub. Commented Jun 22, 2023 at 14:21

1 Answer 1

0

I found out that this is just the case for multi-threaded apartments. To fix this and keep the SynchronizationContext, you'll need to enter a single-threaded apartment by adding the ApartmentAttribute:

[Test, Apartment(ApartmentState.STA)]
public async Task Test_Keeps_SynchronizationContext()
{
    SynchronizationContext.Current.Should().NotBeNull(); // OK
    await Task.Delay(1).ConfigureAwait(true);
    SynchronizationContext.Current.Should().NotBeNull(); // OK
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.