我想斷言ICollection包含滿足一系列約束的項目。對於Java Hamcrest,我會使用Matchers.containsInAnyOrder(Matcher ... matchers)。對於給定的集合,集合中的每個項目都將匹配匹配器中的一個匹配器。在nUnit中,與Hamcrest的Matchers.containsInAnyOrder(Matcher ... matchers)等效的是什麼?
我努力在nUnit 3中找到一個等價物。有一個存在嗎?
我想斷言ICollection包含滿足一系列約束的項目。對於Java Hamcrest,我會使用Matchers.containsInAnyOrder(Matcher ... matchers)。對於給定的集合,集合中的每個項目都將匹配匹配器中的一個匹配器。在nUnit中,與Hamcrest的Matchers.containsInAnyOrder(Matcher ... matchers)等效的是什麼?
我努力在nUnit 3中找到一個等價物。有一個存在嗎?
好吧檢查出的文檔。我對此做了一個光滑的回答。關鍵是創建一個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()));
你想要什麼CollectionEquivalentConstraint,
CollectionEquivalentConstraint測試兩個IEnumerables是等價的 - 它們包含相同的項目,以任何順序。如果傳遞的實際值未實現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
,幾乎我想要做什麼。但這不完全相同。使用CollectionEquivalentConstraints,我給它一個對象集合以進行比較。然後它檢查預期中是否存在一個等於每個對象實際中的一個項目的項目。我想使用一組IConstraint對象。因此,對於實際中的每個對象,它將在預期的匹配器中爲一個項目聲明爲true。 舉一個例子,假設我有數組int [] {1,2},並且我想斷言這是一個具有一個奇數和一個偶數的兩個對象的數組。 –