0

I have a question. I am testing a lib from me, which is generation some text in xml-style. Up to now, I am testing with the function

 Assert.AreEqual(string1, string2);

But the strings, which are in xml-style, are more than 300 characters long. And when I make a little mistake in one character, the test is failing and the output is, that the strings are not equal. But the test does not say, at which position they are not equal.

So my question is: Is there already an implemented function, which compares two strings and tell me also, at which position they differ + output of the strings ... ?

starki
  • 57
  • 7
  • 1
    Take a look into this SO question: http://stackoverflow.com/questions/299553/what-is-the-best-way-to-compare-xml-files-for-equality – Adrian Ciura Nov 28 '14 at 14:59

2 Answers2

2

try this way

var indexBroke = 0;
var maxLength = Math.Min(string1.Length, string2.Length);
while (indexBroke < maxLength && string1[indexBroke] == string2[indexBroke]) {
   indexBroke++;
}
return ++indexBroke;

the logic is that you compare each character step by step and when you get the first difference the function exit returninng the last index with equal characters

faby
  • 7,394
  • 3
  • 27
  • 44
1

For that reason (and many others more), I can recommend using FluentAssertions.

With FluentAssertions you would formulate your assertion like this:

string1.Should().Be(string2);

In the case the strings do not match, you get a nice informative message helping you to tackle down the problem:

Expected string to be 
"<p>Line one<br/>Line two</p>" with a length of 28, but 
"<p>Line one<br>Line two</p>" has a length of 27.

Additionally, you can give a reason to make the error message even more clear:

string1.Should().Be(string2, "a multiline-input should have been successfully parsed");

That would give you the following message:

Expected string to be 
"<p>Line one<br/>Line two</p>" with a length of 28 because a multiline-input should have been successfully parsed, but 
"<p>Line one<br>Line two</p>" has a length of 27.

These reason arguments are especially valuable when comparing values that provide no meaning by themselves, such as booleans and numbers.

BTW, FluentAssertions also helps greatly in comparing object graphs.

paulroho
  • 1,234
  • 1
  • 11
  • 27