我有一个测试方法正在调用 2 个子测试方法。两种子方法都是由 XML 文件驱动的数据。如果我运行每个子方法,它们运行良好且成功。但是,当我运行主测试方法(两个子方法的调用者)时,它发现 TestContext.DataConnection 和 TestContext.DataRow 为空。
private TestContext testContext;
public TestContext TestContext
{
get { return testContext; }
set { testContext = value; }
}
[TestMethod]
public void SaveEmpty_Json_LocalStorage()
{
// Testing JSON Type format export and save
SetWindowsUsers();
// Add Network Information
SetWifiInformation();
// More logic and assertions here.
// More logic and assertions here.
// More logic and assertions here.
}
[TestMethod]
[DeploymentItem("input.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"input.xml",
"User",
DataAccessMethod.Sequential)]
public void SetWindowsUsers()
{
Console.WriteLine(TestContext.DataRow["UserName"].ToString())
// MORE LOGIC and Asserts
}
[TestMethod]
[DeploymentItem("input.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"input.xml",
"WifiList",
DataAccessMethod.Sequential)]
public void SetWifiInformation()
{
Console.WriteLine(TestContext.DataRow["SSID"].ToString())
// MORE LOGIC and Asserts
}
如果我全部运行,2 个方法通过,1 个失败。如果我单独运行, SaveData_Json_LocalStorage 不通过,总是将 TestContext.DataRow 获取为 null。里面调用多个方法可以吗。编写链式测试用例的最佳方式是什么。
最佳答案
仅当必须拥有不可重新创建的数据时才应进行链接。否则使每个测试成为不同的测试。
Data Driven from an XML file.
考虑将只读 Xml 放入一个属性中,该属性在 ClassInitialization
方法中的测试之前运行一次。然后测试各个操作,然后是“主要”操作,每个操作都作为一个单独的可测试单元。
public static XDocument Xml { get; set; }
[DeploymentItem("input.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"input.xml",
"User",
DataAccessMethod.Sequential)]
[ClassInitialize()]
public static void ClassInit(TestContext context)
{ // This is done only once and used by other tests.
Xml = ...
Assert.IsTrue(Xml.Node ... );
}
否则,根据正在执行的测试或来自特定调用的数据来模拟数据,shim
怎么样?看我的文章Shim Saves The Day in A Tricky Unit Test Situation .
关于c# - 单元测试 TestContext 多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30312154/