Find out the next test method to execute in MS TestInitialize

浪尽此生 提交于 2019-12-08 16:35:41

问题


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).


回答1:


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; }
}



回答2:


[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()
    {
    }   
}


来源:https://stackoverflow.com/questions/12194289/find-out-the-next-test-method-to-execute-in-ms-testinitialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!