Find out the next test method to execute in MS TestInitialize
Asked Answered
G

2

13

I keep the test data for specific test method in folder named the same as function. I previously had the same function call in each [TestMethod], ClearAllAndLoadTestMethodData() which determined the method name via StackTrace. Now, I moved this function to [TestInitialize]. How can I find the name of the method that is about to be executed?

I thought TestContext provide this. I have access to it via [AssemblyInitialize()] and on first run its property Name is set to name of the testmethod. However, later this doesn't change (if I save the object in static field).

Groggery answered 30/8, 2012 at 9:56 Comment(0)
C
26

The AssemblyInitialize method is executed only once before all your tests.

Use the TestContext inside the TestInitialize method:

[TestClass]
public class TestClass
{
    [TestInitialize]
    public void TestIntialize()
    {
        string testMethodName = TestContext.TestName;
    }

    [TestMethod]
    public void TestMethod()
    {
    }

    public TestContext TestContext { get; set; }
}
Cohla answered 30/8, 2012 at 13:43 Comment(3)
Thank a lot. I didn't know I have to declare property.Groggery
I was looking for this feature and stumbled upon this great answer. Thanks.Spurt
TestContext is a static property I can see, at least in the 2023 versionRelly
H
0
[TestClass]
public class MyTestClass
{
    private static TestContext _testContext;

    [ClassInitialize]
    public static void TestFixtureSetup(TestContext context)
    {
        _testContext = context;
    }

    [TestInitialize]
    public void TestIntialize()
    {
        string testMethodName = MyTestClass._testContext.TestName;
        switch (testMethodName)
        {
            case "TestMethodA":

                //todo..

                break;
            case "TestMethodB":

                //todo..

                break;              
            default:
                break;
        }
    }

    [TestMethod]
    public void TestMethodA()
    {
    }

    [TestMethod]
    public void TestMethodB()
    {
    }   
}
Harmony answered 27/10, 2019 at 21:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.