我需要比较两个文本块以确定我的单元测试是否通过。不幸的是,这段文本大约有500个字符,如果只有一个字符不同,很难检测出问题所在。MSTest没有告诉我哪些单个字符不同,它只告诉我有差异。在单元测试时,最好的比较文本的方法是什么?(我正在使用MSTest(我考虑过转移到NUnit,但我宁愿不这样做,因为我所有的测试都已经在MSTest中编写了))。
有一个专门为这种情况设计的库Approval Tests。它支持mstest和nunit。
该库是围绕“Golden Copy”测试方法构建的,即主数据集的可信副本,您将准备并验证一次。
[TestClass]
public Tests
{
[TestMethod]
public void LongTextTest()
{
// act: get long-long text
string longText = GetLongText();
//assert: will compare longText variable with file
// Tests.LongTextTest.approved.txt
// if there is some differences,
// it will start default diff tool to show actual differences
Approvals.Verify(longText);
}
}
CollectionAssert
类来进行相关操作。[TestMethod]
public void TestTest()
{
string strA = "Hello World";
string strB = "Hello World";
// OK
CollectionAssert.AreEqual(strA.ToCharArray(), strB.ToCharArray(), "Not equal!");
//Uncomment that assert to see what error msg is when elements number differ
//strA = "Hello Worl";
//strB = "Hello World";
//// Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: CollectionAssert.AreEqual failed. Not equal!(Different number of elements.)
//CollectionAssert.AreEqual(strA.ToCharArray(), strB.ToCharArray(), "Not equal!");
//Uncomment that assert to see what error msg is when elements are actually different
//strA = "Hello World";
//strB = "Hello Vorld";
//// Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: CollectionAssert.AreEqual failed. Not equal!(Element at index 6 do not match.)
//CollectionAssert.AreEqual(strA.ToCharArray(), strB.ToCharArray(), "Not equal!");
}
编写一个辅助函数来进行比较。
if(!String.Equals(textA, textB, StringComparison.OrdinalIgnoreCase))
{
int variesAtIndex = Utilities.DoByteComparison(textA,textB); // can be multiple, return -1 if all good
} // now assert on variesAtIndex`