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)
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);
}
}
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With