了解MSTest TestContext

使用MSTest,我需要从[TestInitialize]方法中获取当前测试的名称。 您可以从TestContext.TestName属性获取此信息。

我发现传入[ClassInitialize]方法的静态TestContext与声明为公共属性的静态TestContext (由测试运行器设置)之间存在意外差异。

请考虑以下代码:

 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( "TextContext.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测试运行器输出复制粘贴):

 TextContext.TestName='TestMethod1' static _testContext.TestName='TestMethod1' TextContext.TestName='TestMethod2' static _testContext.TestName='TestMethod1' TextContext.TestName='TestMethod3' static _testContext.TestName='TestMethod1' 

我曾经假设TestContext的两个实例是等价的,但显然它们不是。

  • public TestContext属性的行为与我期望的一样
  • 传递给[ClassInitialize]方法的private static TestContext值不会。 由于TestContext具有与当前运行的测试相关的属性,因此该实现似乎具有误导性和破坏性

是否有任何情况下您实际上更喜欢使用传递给[ClassInitialize]方法的TestContext ,或者它最好被忽略并且从未使用过?

由于[ClassInitialize]仅在开头调用,因此测试名称为’TestMethod1`。 在第一次测试运行后,这是陈旧的。

为每个方法设置TestContext ,因此具有当前测试名称。

是的,这有点傻。

方法

 [ClassInitialize] public static void SetupTests(TestContext testContext) { } 

在设置属性集TestContext之前调用。 因此,如果您需要SetupTests中的上下文,那么该参数是有用的。 否则使用TestContext属性,该属性在每个属性之前设置

 [TestInitialize] public void SetupTest() { }