Reputation: 149
I am new to the Unit Testing Framework. Using VS 2010, I use an XML as my datasource.
Suppose my XML would look like this:
<testgroup>
<test>
<param1>100</param1>
<param2>200</param2>
</test>
<test>
<param1>333</param1>
<param2>222</param2>
</test>
</testgroup>
So a test group could contain a lot of tests. It wouldn't be efficient to break them out in individual xml files. For simplicity, pretend that param1 is an int and param2 is another int and my test would be to verify that param2 > param1.
Is it possible to write a single TestMethod so that it iterates through the various tests from the XML such that the Unit Test Framework will show a test for each?
I haven't found a solution so far. Perhaps the datasource is not meant to be test data driven this way.
Upvotes: 8
Views: 15546
Reputation: 12375
Using NUnit, you can do the following:
[TestMethod]
public void TestDerpMethod(int a, string b, bool c)
{
//...test code...
}
You can do multiple test cases like so:
[TestMethod]
[TestCase(12, "12", true)]
[TestCase(15, "15", false)]
public void TestDerpMethod(int a, string b, bool c)
{
//...test code...
}
You can also use this method with XML using this method:
<Rows>
<Row>
<A1>1</A1>
<A2>1</A2>
<Result>2</Result>
</Row>
<Row>
<A1>1</A1>
<A2>2</A2>
<Result>3</Result>
</Row>
<Row>
<A1>1</A1>
<A2>-1</A2>
<Result>1</Result>
</Row>
</Rows>
and the C#:
[TestMethod]
[DeploymentItem("ProjectName\\SumTestData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\SumTestData.xml",
"Row",
DataAccessMethod.Sequential)]
public void SumTest()
{
int a1 = Int32.Parse((string)TestContext.DataRow["A1"]);
int a2 = Int32.Parse((string)TestContext.DataRow["A2"]);
int result = Int32.Parse((string)TestContext.DataRow["Result"]);
ExecSumTest(a1, a2, result);
}
private static void ExecSumTest(int a1, int a2, int result)
{
Assert.AreEqual(a1 + a2, result);
}
Upvotes: 15