Understanding the MSTest TestContext

前端 未结 5 1365
一个人的身影
一个人的身影 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:31

    Scenario: context for each test.

    Applies to Visual Studio 2017 with the following libraries:

    • Microsoft.VisualStudio.TestPlatform.TestFramework
    • Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions

    Sample code:

        [TestClass]
        public class MyTestClass
        {
    
            public TestContext TestContext { get; set; }
    
            /// 
            /// Run before each UnitTest to provide additional contextual information.
            /// TestContext reinitialized before each test, no need to clean up after each test.
            /// 
            [TestInitialize]
            public void SetupTest()
            {
                TestContext.Properties.Add("MyKey", "My value ...");
    
                switch (TestContext.TestName)
                {
                    case "MyTestMethod2":
                        TestContext.Properties["MyKey2"] = "My value 2 ...";
                        break;
                }
    
            }
    
            [TestMethod]
            public void MyTestMethod()
            {
                // Usage:
                // TestContext.Properties["MyKey"].ToString()
            }   
    
            [TestMethod]
            public void MyTestMethod2()
            {
                // Usage:
                // TestContext.Properties["MyKey"].ToString()
    
                // also has:
                // TestContext.Properties["MyKey2"].ToString()
            }
    
        }
    

提交回复
热议问题