Visual Studio 2013:测试/断言字符串

时间:2014-11-28 14:35:47

标签: c# string testing visual-studio-2013

我有一个问题。我正在测试一个来自我的lib,它是生成一些xml风格的文本。到目前为止,我正在使用函数

进行测试
 Assert.AreEqual(string1, string2);

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

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

2 个答案:

答案 0 :(得分:2)

试试这种方式

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

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

答案 1 :(得分:1)

出于这个原因(以及更多其他原因),我建议使用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.

这些原因参数在比较自身没有意义的价值时尤为重要,例如布尔值和数字。

BTW,FluentAssertions也有助于比较对象图。