在 nUnit 中,什么与 Hamcrest 的 Matchers.containsInAnyOrder(Matcher... matchers) 等价?

In nUnit, what is the equivalent to Hamcrest's Matchers.containsInAnyOrder(Matcher... matchers)?

我想断言 ICollection 包含将满足约束集合的项。对于 Java Hamcrest,我会使用 Matchers.containsInAnyOrder(Matcher... matchers)。也就是说对于一个给定的集合,集合中的每一项都会匹配一个匹配器中的一个匹配器。

我正在努力寻找 nUnit 3 中的等效项。是否存在?

你要的是CollectionEquivalentConstraint,

CollectionEquivalentConstraint tests that two IEnumerables are equivalent - that they contain the same items, in any order. If the actual value passed does not implement IEnumerable an exception is thrown.

int[] iarray = new int[] { 1, 2, 3 };
string[] sarray = new string[] { "a", "b", "c" };
Assert.That( new string[] { "c", "a", "b" }, Is.EquivalentTo( sarray ) );
Assert.That( new int[] { 1, 2, 2 }, Is.Not.EquivalentTo( iarray ) );

如果您需要更多详细信息,请查看 https://github.com/nunit/docs/wiki/CollectionEquivalentConstraint

中的文档

好的。我对此做了一个巧妙的回答。关键是创建一个 IComparer 来比较约束和对象。它看起来像这样:

/// <summary>
/// A Comparer that's appropriate to use when wanting to match objects with expected constraints.
/// </summary>
/// <seealso cref="System.Collections.IComparer" />
public class ConstraintComparator : IComparer
{
    public int Compare(object x, object y)
    {
        var constraint = x as IConstraint;

        var matchResult = constraint.ApplyTo(y);

        return matchResult.IsSuccess ? 0 : -1;
    }
}

然后我可以执行以下操作:

Assert.That(actual, Is.EquivalentTo(constraints).Using(new ConstraintComparator()));