如何在 TestCleanup 方法中获取 MSTest V2 TestContext 的实例?

How can I get an instance of the MSTest V2 TestContext in the TestCleanup method?

我正在将现有代码库迁移到 MSTest V2,运行 遇到 TestCleanup 方法中 TestContext 的问题。

在 MSTest V1 中,TestContext class 是静态的,但在 V2 中它是一个实例。我试图向 TestCleanup 方法添加一个参数,但随后收到此消息:

The method must be non-static, public, does not return a value and should not take any parameter.

最后我想知道正在清理的测试的名称及其测试结果。如果无法获取 TestContext,是否有任何其他方法可以在清理上下文中获取该信息?

既然TestCleanup方法和TestContext不是静态的,那么你可以在TestCleanup方法中直接使用TestContext而不带任何参数。这是一个例子:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyNamespace.Tests
{
    [TestClass]
    public class MyTestClass
    {
        public TestContext TestContext { get; set; }

        [TestCleanup]
        public void MyTestCleanup()
        {
            TestContext.WriteLine($"Test Cleanup for {TestContext.TestName}");
        }

        [TestMethod]
        public void MyTestMethod1() { }

        [TestMethod]
        public void MyTestMethod2() { }
    }
}