【发布时间】:2017-02-20 19:56:15
【问题描述】:
我想断言 ICollection 包含将满足约束集合的项目。对于 Java Hamcrest,我会使用 Matchers.containsInAnyOrder(Matcher... matchers)。也就是说,对于给定的集合,集合中的每一项都将匹配匹配器中的一个匹配器。
我正在努力寻找 nUnit 3 中的等价物。是否存在?
【问题讨论】:
我想断言 ICollection 包含将满足约束集合的项目。对于 Java Hamcrest,我会使用 Matchers.containsInAnyOrder(Matcher... matchers)。也就是说,对于给定的集合,集合中的每一项都将匹配匹配器中的一个匹配器。
我正在努力寻找 nUnit 3 中的等价物。是否存在?
【问题讨论】:
你想要的是 CollectionEquivalentConstraint,
CollectionEquivalentConstraint 测试两个 IEnumerable 是否等价——它们是否包含相同的项目,顺序不限。如果传递的实际值没有实现 IEnumerable,则会引发异常。
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()));
【讨论】: