Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing text in a unit test

I need to compare two lumps of text for any differences to ascertain whether my unit test has passed or not. Unfortunately the text is about 500 characters long and if only one character differs it is very difficult to detect where the problem lies. MSTest does not tell me which individual characters are different, it just tells me there is a difference.

What's the best way to compare text like this when unit testing?

(I'm using MSTest (I would consider moving to NUnit but I'd rather not as all my tests have already been written in MSTest)

like image 526
atreeon Avatar asked Jan 14 '23 08:01

atreeon


2 Answers

There is a library Approval Tests specially designed for such scenarios. It supports both mstest and nunit.

Library is build around "Golden Copy" testing approach — a trusted copy of a master data set, that you'll prepare and validate once

[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);
    }
}
like image 121
Akim Avatar answered Jan 21 '23 06:01

Akim


You may use MSTest CollectionAssert class.

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

}
like image 32
nikita Avatar answered Jan 21 '23 06:01

nikita