Skip to content

SynchronizationContext not preserved from OneTimeSetup to Test method. #3740

@manfred-brands

Description

@manfred-brands

A test similar to the code below worked in 3.12, but not in 3.13.
It actually works on net5.0 but not on net48.

[TestFixture]
internal sealed class LostSynchronizationContext
{
    private SynchronizationContext m_OriginalSynchronizationContext;
    private TestSynchronizationContext m_TestSynchronizationContext;

    [OneTimeSetUp]
    public void SetContext()
    {
        m_TestSynchronizationContext = new TestSynchronizationContext();
        m_OriginalSynchronizationContext = SynchronizationContext.Current;
        SynchronizationContext.SetSynchronizationContext(m_TestSynchronizationContext);
    }

    [OneTimeTearDown]
    public void ResetContext()
    {
        SynchronizationContext.SetSynchronizationContext(m_OriginalSynchronizationContext);
    }

    [SetUp]
    public void Setup()
    {
        Assert.That(SynchronizationContext.Current, Is.SameAs(m_TestSynchronizationContext));
    }

    [Test]
    public void VerifySynchronized()
    {
        Assert.That(SynchronizationContext.Current, Is.SameAs(m_TestSynchronizationContext));
    }

    public class TestSynchronizationContext : SynchronizationContext
    {
    }
}

The code in ContextUtils captures the current ExecutionContext and then runs it on that same context. @jnm2 Can you explain what that does or do you only actually need the restore part in case a test modifies it and you could call callback(state) directly?

The problem on .NET Framework is that the synchronization context is not preserved: ExecutionContext
Even though the code can, it passes in false to the preserveSyncCtx parameter.

Another option to restore behaviour for .net48 would be to explicitly set the SynchronizationContext in the method passed to ExecutionContext.Run.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions