4

我需要比较两个文本块是否有任何差异,以确定我的单元测试是否通过。不幸的是,文本大约有 500 个字符长,如果只有一个字符不同,就很难发现问题出在哪里。MSTest 没有告诉我哪些个别字符不同,它只是告诉我有区别。

单元测试时比较这样的文本的最佳方法是什么?

(我正在使用 MSTest(我会考虑迁移到 NUnit,但我不想因为我所有的测试都已经用 MSTest 编写过)

4

3 回答 3

6

有一个专门为此类场景设计的库Approval Tests 。它同时支持

库是围绕“黄金副本”测试方法构建的——主数据集的可信副本,您只需准备和验证一次

[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);
    }
}
于 2013-02-01T10:57:12.587 回答
2

您可以使用 MSTestCollectionAssert类。

[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!");

}
于 2013-02-01T10:44:52.487 回答
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`
于 2013-02-01T10:26:32.530 回答