使用MSTest,我需要從[TestInitialize]
方法中獲取當前測試的名稱。你可以從TestContext.TestName
屬性中得到這個。瞭解MSTest TestContext
我發現,在該[ClassInitialize]
方法,一個被聲明爲公共財產(並且得到由測試運行器設置)通過靜態TestContext
之間的行爲意想不到的區別。
考慮下面的代碼:
TextContext.TestName='TestMethod1' static _testContext.TestName='TestMethod1'
TextContext.TestName='TestMethod2' static _testContext.TestName='TestMethod1'
TextContext.TestName='TestMethod3' static _testContext.TestName='TestMethod1'
我以前曾假設:
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的測試運行輸出複製粘貼) TestContext
的兩個實例將是等效的,但顯然它們不是。
- 的
public TestContext
屬性的作用我希望 - 獲取傳遞給
[ClassInitialize]
法private static TestContext
值不。由於TestContext
有涉及到當前正在運行的測試性能,這個實現似乎誤導,打破
是否有一個地方,你會更喜歡使用傳遞給[ClassInitialize]
方法TestContext
任何情況下,或者最好是忽略和從沒用過的?
跑步者在每次測試前創建一個新的TestContext實例。你問爲什麼這樣設計? –
@mikez - 對我來說'私人靜態TestContext'行爲似乎是錯誤的。這就是我所問的。 –
'_testContext'是一個字段,只在您用'[ClassInitialize]'屬性標記的方法內分配一次。你爲什麼期望它在測試之間改變?正如@mike所寫,每個測試都會得到一個新的TestContext實例。 – Groo