单元测试:Nunit(三)
第二部分中提到用XML文件保存测试的案例数据,然后在程序中可以一次性的读取数据,而不需要为每一种可能的数据集合写一个Case。首先,需要定义一个XML的文件,下面是我定义的一个XML文件(CaseFile.xml)。
代码
<?xml version="1.0" encoding="utf-8" ?>
<Nums>
<NumCase>
<Excepted>10</Excepted>
<NumArr>10,9,8,7,6,-2,-2</NumArr>
</NumCase>
<NumCase>
<Excepted>-2</Excepted>
<NumArr>-12,-3,-6,-2,-5,-8,-11</NumArr>
</NumCase>
<NumCase>
<Excepted>5</Excepted>
<NumArr>5,5,5,5</NumArr>
</NumCase>
</Nums>
<Nums>
<NumCase>
<Excepted>10</Excepted>
<NumArr>10,9,8,7,6,-2,-2</NumArr>
</NumCase>
<NumCase>
<Excepted>-2</Excepted>
<NumArr>-12,-3,-6,-2,-5,-8,-11</NumArr>
</NumCase>
<NumCase>
<Excepted>5</Excepted>
<NumArr>5,5,5,5</NumArr>
</NumCase>
</Nums>
那么,下面的任务就是在程序中写一个Test Case来测试是否正确。废话不多说了,直接看代码吧。
代码
[Test]
public void TestGetLargest5()
{
XmlTextReader xmlReader = null;
if (File.Exists("CaseFile.xml")) //读取XML文件
{
xmlReader = new XmlTextReader("CaseFile.xml");
}
if (null == xmlReader) return;
try
{
int excepted = 0;
while (xmlReader.Read()) //循环读取子节点
{
List<int> numList = new List<int>();
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.Name == "Excepted") //找到Excepted节点
{
excepted = Convert.ToInt32(xmlReader.ReadElementString().Trim());
}
else if (xmlReader.Name == "NumArr") //找到NumArr节点
{
String tempNumArr = xmlReader.ReadElementString().Trim();
foreach (string s in tempNumArr.Split(','))
{
numList.Add(Convert.ToInt32(s));
}
int[] numArr = numList.ToArray();
int result = largest.GetLargest(numArr); //调用第二部分中的主程序
Assert.AreEqual(excepted, result); //断言比较
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
finally
{
if (null != xmlReader)
{
xmlReader.Close(); //读取文件的最后不要忘记关闭
}
}
}
public void TestGetLargest5()
{
XmlTextReader xmlReader = null;
if (File.Exists("CaseFile.xml")) //读取XML文件
{
xmlReader = new XmlTextReader("CaseFile.xml");
}
if (null == xmlReader) return;
try
{
int excepted = 0;
while (xmlReader.Read()) //循环读取子节点
{
List<int> numList = new List<int>();
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.Name == "Excepted") //找到Excepted节点
{
excepted = Convert.ToInt32(xmlReader.ReadElementString().Trim());
}
else if (xmlReader.Name == "NumArr") //找到NumArr节点
{
String tempNumArr = xmlReader.ReadElementString().Trim();
foreach (string s in tempNumArr.Split(','))
{
numList.Add(Convert.ToInt32(s));
}
int[] numArr = numList.ToArray();
int result = largest.GetLargest(numArr); //调用第二部分中的主程序
Assert.AreEqual(excepted, result); //断言比较
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
finally
{
if (null != xmlReader)
{
xmlReader.Close(); //读取文件的最后不要忘记关闭
}
}
}
代码本身并不难,主要是要体会在Nunit中常用这种将测试中会用到的多组数据保存在XML或是文本之类的文件中来减少代码的重复性。如果你说,不用XML或是文本而是用像Access或是SQL来保存数据呢,既然这样,那下一部分就针对最常见的CRUD说说数据库的Nunit测试.