了解MSTest TestContext [英] Understanding the MSTest TestContext
问题描述
使用MSTest,我需要从[TestInitialize]
方法中获取当前测试的名称.您可以从TestContext.TestName
属性中获取.
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
property.
我发现传递给[ClassInitialize]
方法的静态TestContext
与声明为公共属性(并由测试运行程序设置)的静态TestContext
在行为上存在意外的差异.
I found an unexpected difference in behaviour between a static TestContext
that is passed in to the [ClassInitialize]
method and one that is declared as a public property (and gets set by the test runner).
考虑以下代码:
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测试运行程序输出中复制粘贴):
This causes the following to be output (copy-pasted from the Resharper test runner output in VS2013):
TestContext.TestName='TestMethod1' static _testContext.TestName='TestMethod1'
TestContext.TestName='TestMethod2' static _testContext.TestName='TestMethod1'
TestContext.TestName='TestMethod3' static _testContext.TestName='TestMethod1'
我以前曾假设TestContext
的两个实例是等效的,但显然它们不是.
I had previously assumed that the two instances of TestContext
would be equivalent, but clearly they're not.
-
public TestContext
属性的行为符合我的预期 - 传递给
[ClassInitialize]
方法的private static TestContext
值没有.由于TestContext
具有与当前正在运行的测试有关的属性,因此此实现似乎会误导和破坏
- The
public TestContext
property behaves as I expect - The
private static TestContext
value that gets passed to the[ClassInitialize]
method does not. SinceTestContext
has properties that relate to the currently running test, this implementation seems misleading and broken
在任何情况下,您实际上是否更喜欢使用传递给[ClassInitialize]
方法的TestContext
,还是最好将其忽略并且永远不要使用?
Is there any scenario where you would actually prefer to use the TestContext
passed to the [ClassInitialize]
method, or it is best ignored and never used?
推荐答案
由于仅在开头调用[ClassInitialize]
,因此测试名称为TestMethod1
.在第一次测试运行后,这已经过时了.
As [ClassInitialize]
is only called at the beginning, the test name is TestMethod1
. This is stale after the first test run.
TestContext
为每种方法设置,因此具有当前的测试名称.
TestContext
is set for every method, and thus has the current test name.
是的,这有点愚蠢.
这篇关于了解MSTest TestContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!