Visual Studio 2013: Testing / Assert Strings

本文关键字:Assert Strings Testing Studio 2013 Visual | 更新日期: 2023-09-27 18:32:31

我有一个问题。我正在测试我的一个库,它是以 xml 风格生成一些文本。到目前为止,我正在使用该功能进行测试

 Assert.AreEqual(string1, string2);

但是 xml 样式的字符串长度超过 300 个字符。当我在一个字符中犯了一个小错误时,测试失败了,输出是字符串不相等。但是测试并没有说,他们在哪个位置不平等。

所以我的问题是:是否已经有一个实现的函数,它比较两个字符串并告诉我,它们在哪个位置不同 + 字符串的输出......?

Visual Studio 2013: Testing / Assert Strings

试试这种方式

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

逻辑是逐步比较每个字符,当您得到第一个差异时,函数 exit 返回具有相等字符的最后一个索引

出于这个原因(以及许多其他原因),我可以推荐使用FluentAssertions。

使用FluentAssertions,你可以像这样表述你的断言:

string1.Should().Be(string2);

如果字符串不匹配,您将获得一条很好的信息性消息,帮助您解决问题:

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.

此外,您可以给出一个原因,使错误消息更加清晰:

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

这将为您提供以下消息:

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.

在比较本身没有意义的值(如布尔值和数字)时,这些原因参数特别有价值。

顺便说一句,FluentAssertions在比较对象图方面也有很大帮助。