TestContext

TestContext 类提供了有用的信息和工具来帮助管理测试执行。 它允许你访问有关测试运行的详细信息并调整测试环境。 此类是 Microsoft.VisualStudio.TestTools.UnitTesting 命名空间的一部分。

访问 TestContext 对象

TestContext 对象在以下上下文中可用:

  • 作为 AssemblyInitialize 的参数,ClassInitialize 方法。 在此上下文中,与测试运行相关的属性不可用。
  • 从 3.6 开始,(可选)作为 AssemblyCleanup 的参数,ClassCleanup 方法。 在此上下文中,与测试运行相关的属性不可用。
  • 作为测试类的属性。 在此上下文中,与测试运行相关的属性可用。
  • 作为测试类的构造器参数(从 v3.6 开始)。 建议使用这种方式,而不是使用属性,因为这样可以在构造函数中访问对象。 而该属性仅在构造函数运行后可用。 这种方式还有助于确保对象的不可变性,并允许编译器强制对象不为 null。
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClassTestContext
{
    public TestContext TestContext { get; set; }

    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        // Access TestContext properties and methods here. The properties related to the test run are not available.
    }

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        // Access TestContext properties and methods here. The properties related to the test run are not available.
    }

    [TestMethod]
    public void MyTestMethod()
    {
        // Access TestContext properties and methods here
    }
}

或者可以使用 MSTest 3.6+:

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClassTestContextThroughCtor
{
    private readonly TestContext _testContext;

    public MyTestClassTestContextThroughCtor(TestContext testContext)
    {
        _testContext = testContext;
    }

    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        // Access TestContext properties and methods here. The properties related to the test run are not available.
    }

    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        // Access TestContext properties and methods here. The properties related to the test run are not available.
    }

    [TestMethod]
    public void MyTestMethod()
    {
        // Access TestContext properties and methods here
    }
}

TestContext成员。

TestContext 类提供有关测试运行的属性以及用于操作测试环境的方法。 本部分介绍最常用的属性和方法。

测试运行信息

TestContext 提供测试运行的相关信息,如:

在 MSTest 3.7 及更高版本中,TestContext 类还提供对 TestInitializeTestCleanup 方法有用的新属性:

数据驱动的测试

在 MSTest 3.7 及更高版本中,属性 TestContext.TestData 可用于在 TestInitializeTestCleanup 方法期间访问当前测试的数据。

在面向 .NET Framework 时,TestContext 允许你使用 DataRowDataConnection 属性来检索和设置数据驱动测试中每次迭代的数据(适用于基于 DataSource的测试)。

请考虑以下 CSV 文件 TestData.csv

Number,Name
1,TestValue1
2,TestValue2
3,TestValue3

可以使用 DataSource 属性从 CSV 文件读取数据:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace YourNamespace
{
    [TestClass]
    public class CsvDataDrivenTest
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        [DataSource(
            "Microsoft.VisualStudio.TestTools.DataSource.CSV",
            "|DataDirectory|\\TestData.csv",
            "TestData#csv",
            DataAccessMethod.Sequential)]
        public void TestWithCsvDataSource()
        {
            // Access data from the current row
            int number = Convert.ToInt32(TestContext.DataRow["Number"]);
            string name = TestContext.DataRow["Name"].ToString();

            Console.WriteLine($"Number: {number}, Name: {name}");

            // Example assertions or logic
            Assert.IsTrue(number > 0);
            Assert.IsFalse(string.IsNullOrEmpty(name));
        }
    }
}

存储和检索运行时数据

可以使用 TestContext.Properties 来存储可在同一测试会话中跨不同方法访问的自定义键值对。

TestContext.Properties["MyKey"] = "MyValue";
string value = TestContext.Properties["MyKey"]?.ToString();

将数据关联到测试

TestContext.AddResultFile(String) 方法允许向测试结果添加文件,使其在测试输出中可供查看。 这在您希望将测试期间生成的文件(例如日志文件、屏幕截图或数据文件)附加到测试结果时,非常有用。

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class TestClassResultFile
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    public void TestMethodWithResultFile()
    {
        // Simulate creating a log file for this test
        string logFilePath = Path.Combine(TestContext.TestRunDirectory, "TestLog.txt");
        File.WriteAllText(logFilePath, "This is a sample log entry for the test.");

        // Add the log file to the test result
        TestContext.AddResultFile(logFilePath);

        // Perform some assertions (example only)
        Assert.IsTrue(File.Exists(logFilePath), "The log file was not created.");
        Assert.IsTrue(new FileInfo(logFilePath).Length > 0, "The log file is empty.");
    }
}

还可以使用 TestContext.WriteTestContext.WriteLine 方法将自定义消息直接写入测试输出。 这对于调试非常有用,因为它在测试执行上下文中提供实时日志记录信息。