FluentAssertion 无法比较字符串的可枚举性
这段代码工作正常
[Test]
public void boo()
{
var collection = new[] { 1, 2, 3 };
collection.Should().Equal(1, 2, 3);
}
但是,这失败了
[Test]
public void foo()
{
var collection = new[] { "1", "2", "3" };
collection.Should().Equal("1", "2", "3");
}
失败消息是:
'预期集合等于 {1},因为 2,但是 {"1", "2", "3"} 包含 2 项太多。'
这里有什么问题吗?为什么字符串的可枚举性无法比较?
当然,我的问题是 - 如何处理 foo() 中的情况?
This code works fine
[Test]
public void boo()
{
var collection = new[] { 1, 2, 3 };
collection.Should().Equal(1, 2, 3);
}
But, this fails
[Test]
public void foo()
{
var collection = new[] { "1", "2", "3" };
collection.Should().Equal("1", "2", "3");
}
The failure message is:
'Expected collection to be equal to {1} because 2, but {"1", "2", "3"}
contains 2 item(s) too many.'
What is wrong here? Why enumerable of string could not be compared?
And, of cause, my question is - how to handle case in foo() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是第二个调用被解析为以下重载:
而不是:
要获得所需的结果,您可以强制编译器使用正确的重载方法,例如通过执行以下操作:
The problem is that the 2nd call is resolved to the following overload:
Instead of:
To get the desired result you can force the compiler to the right overload method, for example by doing:
发生这种情况的原因是,由于 C# 的限制,编译器选择了错误的 Equals() 重载。在您的特定情况下,它采用 Equals(string Expected, string Reason, params string[] args),而不是 Equals(IEnumerable)。我从未找到一种简单的方法来解决 FluentAssertions 中的这种歧义。
要解决您的问题,请将预期值包装在数组中。
This happens because the compiler selects the wrong overload of Equals() because of limitations in C#. In your particular case, it's taking the Equals(string expected, string reason, params string[] args), instead of Equals(IEnumerable). I have never found an easy way to solve this ambiguity in FluentAssertions.
To solve your problem, wrap the expected values in an array.
测试会发生什么:
我假设肯尼在评论中承认您正在执行引用相等,其中这些字符串不是相同的引用。
What happens with the test of:
I assume as Kenny acknowledged in a comment that you're doing reference equality where those strings are not the same reference.
尝试使用 SequenceEquals 来代替吗?
http://msdn.microsoft.com/en-us/library/bb342073.aspx
而 Equals 方法只是比较引用是否相等。
这是我的一个项目中的单元测试中的一行:
“预期”和“实际”中的所有元素都实现 IEQuatable。
Try SequenceEquals instead?
http://msdn.microsoft.com/en-us/library/bb342073.aspx
And the Equals method is just comparing the references for equality.
Here's a line from a unit test in one of my projects:
All of the elements in "expected" and "actual" implement IEQuatable.