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)

Waescher
  • 5,361
  • 3
  • 34
  • 51
  • Have you asked the NUnit team? – Stephen Cleary Jun 22 '23 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](https://github.com/nunit/nunit/issues/4407). – Waescher Jun 22 '23 at 14:21

1 Answers1

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
}
Waescher
  • 5,361
  • 3
  • 34
  • 51