问题描述
在 C#'s NUnit framework 中有 Is.EquivalentTo
约束,它对于断言两个数组在“排列”方式中是等效的非常有用(即元素的顺序无关紧要,只有内容。 )
例如以下测试将通过
[Test]
public void test()
{
Assert.That(new[] { 1,2,3 },Is.EquivalentTo(new[] { 2,3,1 }));
}
我一直在想,有没有办法对锯齿状数组应用相同的约束? 我想做以下事情
[Test]
public void Test2D()
{
// expected true,but fails
Assert.That(new[] { new[] { 1 },new[] { 2,3 } },Is.EquivalentTo(new[] { new[] { 3,2 },new[] { 1 } }));
}
解决方法
由于 NUnit 中的等价定义,您的示例将不起作用。
NUnit 接受两个枚举(在本例中为外部数组)并检查内容是否相等不考虑顺序。
所以这会通过:
Assert.That(new[] { new[] { 1 },new[] { 2,3 } },Is.EquivalentTo(new[] { new[] { 2,3 },new[] { 1 } }));
您的示例 OTOH 失败了,因为您希望将等效性应用于集合中的各个项目以及集合本身。
正如已经指出的那样,您可以定义自己的相等比较器并将其与 .Using()
修饰符一起应用。这就是我在这种情况下会做的。
感谢所有贡献。
我想介绍我解决这个问题的方法。
我只是对内部数组进行排序,然后使用 Is.EquivalentTo()
[Test]
public void Test2D()
{
var actual = new[] { new[] { 1 },3 } }
.Select(x => x.OrderBy(e => e));
var expected = new[] { new[] { 3,2 },new[] { 1 } }
.Select(x => x.OrderBy(e => e));
Assert.That(actual,Is.EquivalentTo(expected));
}