Skip to content

Regression: AsyncLocal loses value since v3.9.* #5687

@N-Olbert

Description

@N-Olbert

Describe the bug

A regression has been introduced in version 3.9.* that affects the behavior of AsyncLocal in async test methods, most likely by #5646. Specifically, when using a custom TestMethodAttribute to set AsyncLocal state, the value is unexpectedly lost in within the actual test method. This behavior was not present in versions prior to v3.9.* .
It only happens if an AssemblyInitialize-Method is present.

Steps To Reproduce

namespace Tests;

[TestClass]
public class AssemblyOperations
{
    [AssemblyInitialize]
    public static async Task AssemblyInitialize(TestContext context)
    {
        Assert.AreEqual(null, AsyncLocalState.State.Value);
        await Task.Delay(1);
    }
}

[TestClass]
public sealed class Test1
{
    [PreparedAsyncLocalStateTestMethod]
    public void TestMethodSync()
    {
        // Assert is successful in 3.8.* but not in 3.9.*
        Assert.AreEqual("Foo", AsyncLocalState.State.Value); 
    } 
    
    
    [PreparedAsyncLocalStateTestMethod]
    public async Task TestMethodAsync()
    {
        // Assert is successful in 3.8.* but not in 3.9.*
        Assert.AreEqual("Foo", AsyncLocalState.State.Value);
        await Task.Delay(1);
    } 
}

public class AsyncLocalState
{
    public static AsyncLocal<object> State = new();
}

public class PreparedAsyncLocalStateTestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        AsyncLocalState.State.Value = "Foo";
        Assert.AreEqual("Foo", AsyncLocalState.State.Value);
        return base.Execute(testMethod);
    }
}

Expected behavior

All tests pass.

Actual behavior

All tests fail (the assertation within the [AssemblyInitialize]-method passes.

Additional context

Metadata

Metadata

Assignees

Labels

Area: MSTestIssues with MSTest that are not specific to more refined area (e.g. analyzers or assertions)Regression

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions