我需要比较两个文本块的差异,以确定我的单元测试是否已通过。不幸的是,文本长度大约为500个字符,如果只有一个字符不同,则很难发现问题所在。 MSTest没有告诉我哪些个性字符不同,它只是告诉我存在差异。
在单元测试中比较这样的文本的最佳方法是什么?
(我正在使用MSTest(我会考虑转移到NUnit,但我不愿意,因为我的所有测试都已在MSTest中编写)
答案 0 :(得分:6)
有一个专门为此类场景设计的库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);
}
}
答案 1 :(得分:1)
写一个帮手进行比较。
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`
答案 2 :(得分:1)
您可以使用MSTest 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!");
}