c#-ClassInitialize上的数据驱动单元测试
作者:互联网
我试图每次使用不同的值运行一些测试.例如:我有3种方法:methodA,methodB和methodC.我想在不同的索引位置运行两次每个方法.我有TestInitialize和ClassInitialize方法.
>我尝试使用ClassInitialize,但未成功;我收到编译时错误,因为我的测试上下文不是静态的.
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[DeploymentItem("UI.Framework.IntegrationTests\\ExpectedValues.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\ExpectedValues.xml", "searchTerm2", DataAccessMethod.Sequential)]
[ClassInitialize()]
publicstaticvoid ClassInitialize(TestContext context)
{
string indexPath = TestContext.DataRow[0].ToString();
bool isSuccess1 = SearchApiTestsHelper.InitializeSearchEngine(indexPath, null);
Assert.IsTrue(isSuccess1);
}
我做不到
>我尝试使用TestInitialize,但未加载数据行,它为null.
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\ExpectedValues.xml",
"indices",
DataAccessMethod.Sequential),
TestInitialize()]
public void MyTestInitialize()
{
string indexPath = TestContext.DataRow[0].ToString();
bool isSuccess1 = SearchApiTestsHelper.InitializeSearchEngine(indexPath, null);
Assert.IsTrue(isSuccess1);
}
>我知道我可以将每个方法设置为运行两次,但是,某些方法需要不同的数据进行验证.例如method2仍需要为每个索引位置运行两次,并且每次运行都声明来自数据源的一组期望值.
[DeploymentItem("UI.Framework.IntegrationTests\\ExpectedValues.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\ExpectedValues.xml",
"pb1", DataAccessMethod.Sequential),
TestCategory("Integration")]
[TestMethod]
public void PhraseBoosting()
{
expectedVal = TestContext.DataRow[0].ToString();
}
如何将其归档?
解决方法:
假设这样的XML文件:
<Values>
<searchTerm2>this is search term 2</searchTerm2>
<indices>these are the indices</indices>
<pb1>personal best?</pb1>
</Values>
您可以像这样访问这些值:
[TestClass]
public class UnitTest1
{
public TestContext TestContext
{
get;
set;
}
//[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\ExpectedValues.xml", "Values", DataAccessMethod.Sequential)]
//[ClassInitialize]
//public static void ClassInitialize(TestContext testContext)
//{
// string indexPath = testContext.DataRow["searchTerm2"].ToString();
// Console.WriteLine(indexPath);
//}
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\ExpectedValues.xml", "Values", DataAccessMethod.Sequential)]
[TestInitialize]
public void TestInitialize()
{
string indexPath = TestContext.DataRow["indices"].ToString();
Console.WriteLine(indexPath);
}
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\ExpectedValues.xml", "Values", DataAccessMethod.Sequential)]
[TestMethod]
public void TestMethod1()
{
string indexPath = TestContext.DataRow["pb1"].ToString();
Console.WriteLine(indexPath);
}
}
类的initialize方法似乎不起作用.我不确定这是否是设计使然.
标签:testing,mstest,c 来源: https://codeday.me/bug/20191030/1970709.html