Understanding the MSTest TestContext

前端 未结 5 1369
一个人的身影
一个人的身影 2020-12-14 07:03

Using MSTest, I needed to obtain the name of the current test from within the [TestInitialize] method. You can get this from the TestContext.TestName

5条回答
  •  春和景丽
    2020-12-14 07:16

    If you want to pass your objects created in method [ClassInitialize] (or[AssemblyInitialize]) to the cleanup methods and your tests, you must keep its initialization context in a separate static variable, aside from the regular TestContext. Only this way can you retrieve it later in your code.

    public TestContext TestContext { get; set; } // regular test context
    private static TestContext ClassTestContext { get; set; } // global class test context
    
    [ClassInitialize]
    public static void ClassInit(TestContext context)
    {
            ClassTestContext = context;
            context.Properties["myobj"] = ;
    }
    
    [ClassCleanup]
    public static void ClassCleanup()
    {
        object myobj = (object)ClassTestContext.Properties["myobj"];
    }
    
    [TestMethod]
    public void Test()
    {
        string testname = (string)TestContext.Properties["TestName"] // object from regular context
        object myobj = (object)ClassTestContext.Properties["myobj"]; // object from global class context
    }
    

    MSTest framework does not preserve the context objects passed to [ClassInitialize]/[AssemblyInitialize] method, so after the return they will be lost forever unless you explicitly save them.

提交回复
热议问题