使用 MSTest,我需要从[TestInitialize]
方法中获取当前测试的名称。你可以从酒店得到这个TestContext.TestName
。
TestContext
我发现传递给[ClassInitialize]
方法的静态变量和声明为公共属性(并由测试运行程序设置)的静态变量之间的行为存在意外差异。
考虑以下代码:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestContext.Tests
{
[TestClass]
public class UnitTest1
{
public TestContext TestContext { get; set; }
private static TestContext _testContext;
[ClassInitialize]
public static void SetupTests(TestContext testContext)
{
_testContext = testContext;
}
[TestInitialize]
public void SetupTest()
{
Console.WriteLine(
"TestContext.TestName='{0}' static _testContext.TestName='{1}'",
TestContext.TestName,
_testContext.TestName);
}
[TestMethod] public void TestMethod1() { Assert.IsTrue(true); }
[TestMethod] public void TestMethod2() { Assert.IsTrue(true); }
[TestMethod] public void TestMethod3() { Assert.IsTrue(true); }
}
}
这会导致输出以下内容(从 VS2013 中的 Resharper 测试运行器输出复制粘贴):
TestContext.TestName='TestMethod1' static _testContext.TestName='TestMethod1'
TestContext.TestName='TestMethod2' static _testContext.TestName='TestMethod1'
TestContext.TestName='TestMethod3' static _testContext.TestName='TestMethod1'
我之前假设两个实例TestContext
是等价的,但显然它们不是。
- 该
public TestContext
物业的行为符合我的预期 private static TestContext
传递给该方法的值[ClassInitialize]
不会。由于TestContext
具有与当前正在运行的测试相关的属性,因此此实现似乎具有误导性和破坏性
是否有任何情况下您实际上更喜欢使用TestContext
传递给方法的[ClassInitialize]
方法,或者最好忽略它并且从不使用它?