问题描述
我正在尝试使用 Fluent Assertions 来测试排列生成算法。该算法生成一个 List<int[]>
,其中 List
的顺序无关紧要,但每个 int[]
的元素都重要。
[Fact]
public void Are_all_permutations_generated()
{
// Arrange
var expected = new List<int[]>
{
new[] { 1,2,3 },new[] { 1,3,2 },new[] { 2,1,1 },new[] { 3,1 }
};
// Act
var result = new List<int[]>
{
new[] { 3,3 }
};
// Assert
result.Should().BeEquivalentTo(expected);
}
如果我在上面的代码块中使用 result.Should().BeEquivalentTo(expected)
,即使 result
是
var result = new List<int[]>
{
new[] { 1,3 }
};
如何编写 Fluent Assertions 以允许列表的任何顺序,但对数组进行严格排序,以便它可以断言已找到所有排列?有没有办法在 options
中写入 BeEquivalentTo
来做到这一点?
解决方法
使用 WithStrictOrderingFor
确定何时要使用严格排序。它需要一个 lambda 来让您访问 IObjectInfo
,这是一个公开您可以使用的各种相关信息的对象。类似的东西
WithStrictOrderingFor(info => info.RuntimeType == typeof(int[]))
,
您可以尝试在数组断言上使用 WithStrictOrdering
。
例如:
result.Should().BeEquivalentTo(expected,options => options.WithStrictOrdering());
您还可以查看 FluentAssertion 的 collection assertion docs,它们提供了更多关于如何比较集合的选项。