我有一个类可以处理 2 个 xml 文件并生成一个文本文件。
我想编写一堆单元/集成测试,这些测试可以单独为这个类通过或失败,它们执行以下操作:
- 对于输入 A 和 B,生成输出。
- 将生成文件的内容与预期输出的内容进行比较
- 当实际内容与预期内容不同时,失败并显示一些关于差异的有用信息。
下面是该类的原型以及我在单元测试中的第一次尝试。
有没有我应该用于这种测试的模式,还是人们倾向于编写数以万计的 TestX() 函数?
有没有更好的方法来哄骗 NUnit 的文本文件差异?我应该嵌入文本文件差异算法吗?
class ReportGenerator
{
string Generate(string inputPathA, string inputPathB)
{
//do stuff
}
}
[TextFixture]
public class ReportGeneratorTests
{
static Diff(string pathToExpectedResult, string pathToActualResult)
{
using (StreamReader rs1 = File.OpenText(pathToExpectedResult))
{
using (StreamReader rs2 = File.OpenText(pathToActualResult))
{
string actualContents = rs2.ReadToEnd();
string expectedContents = rs1.ReadToEnd();
//this works, but the output could be a LOT more useful.
Assert.AreEqual(expectedContents, actualContents);
}
}
}
static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
[Test]
public void TestX()
{
TestGenerate("x1.xml", "x2.xml", "x-expected.txt");
}
[Test]
public void TestY()
{
TestGenerate("y1.xml", "y2.xml", "y-expected.txt");
}
//etc...
}
更新
我对测试差异功能不感兴趣。我只是想用它来产生更具可读性的失败。