Skip to content

TestContext.Properties across test methods of same class is different instance #5986

Closed

Description

Context

As per the docs here:

You can use TestContext.Properties to store custom key-value pairs that can be accessed across different methods in the same test session.

Scenario

In my scenario, I'm trying to mock a file/folder structure in memory (using a library for this purpose) and then run multiple test methods against that same data setup. In ClassInitialize I store this memory structure in the Properties bag to retrieve in each test method (as indicated possible by the docs).

[TestClass]
public sealed class TestSync
{
    private readonly TestContext _testContext;

    public TestSync(TestContext testContext)
    {
        Debug.WriteLine($"Construct TestSync has TestContext: {testContext.GetHashCode()}");
        _testContext = testContext;
    }

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        // Access TestContext properties and methods here. The properties related to the test run are not available.
        Debug.WriteLine($"ClassInitialize TestSync passed TestContext: {context.GetHashCode()}");

        context.Properties["TestPropertyClass"] = "TestValue2";
    }

    [TestMethod]
    public void TestMethod1Sync()
    {
        Debug.WriteLine($"TestMethod1Sync has TestContext: {_testContext.GetHashCode()}");
        
        Assert.IsTrue(_testContext.Properties.Contains("TestPropertyClass"), "TestPropertyClass key should have been set in ClassInitialize.");
        Assert.AreEqual("TestValue2", _testContext.Properties["TestPropertyClass"], "TestPropertyClass value should equal 'TestValue2'.");
    }

    [TestMethod]
    public void TestMethod2Sync()
    {
        Debug.WriteLine($"TestMethod2Sync has TestContext: {_testContext.GetHashCode()}");

        Assert.IsTrue(_testContext.Properties.Contains("TestPropertyClass"), "TestPropertyClass key should have been set in ClassInitialize.");
        Assert.AreEqual("TestValue2", _testContext.Properties["TestPropertyClass"], "TestPropertyClass value should equal 'TestValue2'.");
    }
}

Background

As per the original lifecycle thread, this was the behavior I was seeing:

I'm seeing the same oddness with the AssemblyInitialize. If I run each test individually, it'll work and I see AssemblyInitialize called for each one. When I run them both together though, one will see the context set and the other one won't. Shouldn't the AssemblyInitialize run and be able to store a property before either class is constructed?

Though, this is a similar behavior to what I'm seeing with my ClassInitialize in my project, I just noticed I have both my tests in the same class there compared to creating different classes in the repro. i.e. if I run either test within the same class individually it'll pass with the proper stored context provided in the ClassInitialize. However, if I run the whole thing together, I see two different TestContext objects being passed. One has been initialized by ClassInitialize and the other is some other object (I also see the constructor called twice instead of once).

I'll open a new bug with my repro as an example, I have it where each test will pass individually with a full lifecycle run, but non-deterministically fail when run all together as they're all getting passed different contexts instead of sharing one (or two - I'm not quite sure how the TestContext property bag is supposed to be handled in the assembly case with two classes...).

Originally posted by Michael A. Hawker (@hawkerm) in #5637

Repro

MSTestContext.zip

  1. Attached is a small repro project, you should be able to open it in VS and run the tests there.
  2. If you run each test individually, they'll pass:
Image
  1. However, if you run them all at once, they non-deterministically fail.
Image Image

Expect: All tests to pass when run together (or at least the ones in the same class).

Extra information

I guess it's not well defined the expectation of properties stored in the AssemblyInitialize phase. I would expect/hope naively that some sort of clone of that context/property bag is made per test class? There's probably a couple of issues here, I think the class one is the most unexpected.

If the written code is not how TestContext is supposed to be utilized, then the doc section here should be updated with a complete example and analyzers added to detect inappropriate usage (if possible to detect).

Activity

  1. Youssef1313 commented on Jul 11, 2025

    @Youssef1313
    Member

    Amaury Levé (@Evangelink) What's your expectation here for TestContext.Properties? 😕

  2. added
    needs/design
    area/mstest
    and removed
    needs/triage
    on Jul 11, 2025
  3. Youssef1313 commented on Jul 11, 2025

    @Youssef1313
    Member

    Note that if we will share TestContext.Properties across test methods, then it must be ConcurrentDictionary instead of Dictionary. But the dictionary also used to store things like test name etc, so it cannot be the same instance across all test methods. But we could still ensure sharing user-set properties in all test contexts.

  4. hawkerm commented on Jul 12, 2025

    @hawkerm
    Author

    Thanks Youssef Fahmy (@Youssef1313) for the quick response. I'm definitely curious what the intended behavior is.

    I was just comparing your original breakdown of lifecycle in #5637, that made it a bit clearer that I also didn't realize a new class instance is constructed for every test (I don't think I picked that up from the doc page). Maybe I'll submit a PR there for some more improvements once I get this sorted a bit more in my mind, but it'd be great to know what a sample for sharing some common setup/data for a test would look like.

  5. Evangelink commented on Jul 12, 2025

    @Evangelink
    Member

    I have to admit I haven't really worked with the properties so I'm not sure what was the original intent of MSTest. Because everything was designed as non-parallel I'm not so surprised there are concurrency issues.

    Overall it makes sense to me to have a common container of properties with the risks associated. It's called blackboard in Behavior Tree Testing.

    We should probably (hidden from users) have 2 collections, one global and one per test so we don't have properties like test name being invalid.

  6. Youssef1313 commented on Jul 12, 2025

    @Youssef1313
    Member

    We should probably (hidden from users) have 2 collections, one global and one per test so we don't have properties like test name being invalid.

    Yup. That's my thought as well. It's a question of "does it make sense to make user-defined properties shared between tests?"

    I think it could make sense to share properties between steps, like anything set in Asm Init will be available every where, etc. But I have doubts on sharing between different test methods, or sharing between different test classes.

  7. Evangelink commented on Jul 15, 2025

    @Evangelink
    Member

    I have never used these patterns personally, but I have seen it in some books and articles:

    1. Sequential tests, each step is setting some "state" for the next test. Mitigation: user could use local state (field/property).
    2. Each test of the current class sets some flag, and the class cleanup does some action based on available flags. Mitigation: user could use static state (field/property).

    Michael A. Hawker (@hawkerm) about your real-life scenario, do you need to share the state within a single class or across classes?

  8. RussKie commented on Sep 3, 2025

    @RussKie

    Just hit this today. I expected that I could set shared state in ClassInitialize method - in my case temp folder to be used by all tests, and in each test, I could get access to those properties.

        public TestContext TestContext { get; set; }
    
        [ClassInitialize]
        public static void Setup(TestContext context)
        {
            string testFolder = Path.Combine(Path.GetTempPath(), "BuildHandlerTests");
            context.Properties["BuildHandlerTests_Folder"] = testFolder;
        }
    
        [ClassCleanup(cleanupBehavior: ClassCleanupBehavior.EndOfClass)]
        public static void Cleanup(TestContext context)
        {
            string testFolder = context.Properties["BuildHandlerTests_Folder"] as string ?? string.Empty;
            if (Directory.Exists(testFolder))
                Directory.Delete(testFolder, true);
        }
    
        [TestMethod]
        public async Task Run_CreatesDirectoryPackagesProps()
        {
            string testFolder = TestContext.Properties["BuildHandlerTests_Folder"] as string ?? string.Empty;
            
            // test logic
        }
  9. Youssef1313 commented on Sep 3, 2025

    @Youssef1313
    Member

    Igor Velikorossov (@RussKie) Is this a regression compared to earlier version? or trying to write new code?

    I think it makes sense to try to share properties between different test steps, similar to how we flow async locals.

    In your specific case as you only write to the dictionary in class initialize and read in other steps, I think you can simply use an async local. Something like:

        private static readonly AsyncLocal<Dictionary<string, string>> s_localProperties;
    
        [ClassInitialize]
        public static void Setup(TestContext context)
        {
            s_localProperties = new();
            s_localProperties.Value = new();
            string testFolder = Path.Combine(Path.GetTempPath(), "BuildHandlerTests");
            s_localProperties.Value["BuildHandlerTests_Folder"] = testFolder;
        }
    
        [ClassCleanup(cleanupBehavior: ClassCleanupBehavior.EndOfClass)]
        public static void Cleanup(TestContext context)
        {
            s_localProperties.Value["BuildHandlerTests_Folder"] as string ?? string.Empty;
            if (Directory.Exists(testFolder))
                Directory.Delete(testFolder, true);
        }
    
        [TestMethod]
        public async Task Run_CreatesDirectoryPackagesProps()
        {
            string testFolder = s_localProperties.Value["BuildHandlerTests_Folder"] as string ?? string.Empty;
            
            // test logic
        }
  10. hawkerm commented on Oct 2, 2025

    @hawkerm
    Author

    Amaury Levé (@Evangelink) I think in this case I was just looking to share across a class and multiple tests within that class. As I had mentioned above I did see new test class instances being created for every test method within a class which I found unexpected.

    For the time being back in July when I stumbled upon this, I ended up switching to TestInitialize and just storing a reference to a field within the class of my object, but it's still getting recreated for each test vs. being shared, but in some ways that's a better thing to ensure test isolation.

    e.g. For my original example, something like this instead now:

    [TestClass]
    public sealed class TestSync
    {
        private readonly TestContext _testContext;
    
        private string _testValue;
    
        public TestSync(TestContext testContext)
        {
            Debug.WriteLine($"Construct TestSync has TestContext: {testContext.GetHashCode()}");
            _testContext = testContext;
        }
    
        [TestInitialize]
        public static void TestInit()
        {
            // Access TestContext properties and methods here. The properties related to the test run are not available.
            Debug.WriteLine($"TestInitialize TestSync passed TestContext: {_testContext}");
    
            _testValue = "TestValue2";
        }
    
        [TestMethod]
        public void TestMethod1Sync()
        {
            Debug.WriteLine($"TestMethod1Sync has TestContext: {_testContext.GetHashCode()}");
            
            Assert.AreEqual("TestValue2", _testValue, "_testValue value should equal 'TestValue2'.");
        }
    
        [TestMethod]
        public void TestMethod2Sync()
        {
            Debug.WriteLine($"TestMethod2Sync has TestContext: {_testContext.GetHashCode()}");
    
            Assert.AreEqual("TestValue2", _testValue, "_testValue value should equal 'TestValue2'.");
        }
    }

    Figured I'd share in case anyone was looking for a workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/mstestneeds/design

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions