Collection Constraints (NUnit 2.4)
Collection constraints perform tests that are specific to collections. The following collection constraints are provided.
Syntax Helper | Constructor | Operation |
---|---|---|
Is.All... Has.All... | AllItemsConstraint( Constraint ) | applies a constraint to each item in a collection, succeeding only if all of them succeed |
Has.Some... | SomeItemsConstraint( Constraint ) | applies a constraint to each item in a collection, succeeding if at least one of them succeeds |
Has.None... | NoItemConstraint( Constraint ) | applies a constraint to each item in a collection, succeeding only if all of them fail |
Is.Unique | UniqueItemsConstraint() | tests that a collection contains only unique items |
Has.Member( object ) | CollectionContainsConstraint( object ) | tests that a collection contains an object |
Is.EquivalentTo( IEnumerable ) | CollectionEquivalentConstraint( ICollection ) | tests that two collections are equivalent |
Is.SubsetOf( IEnumerable ) | CollectionSubsetConstraint( ICollection ) | tests that one collection is a subset of another |
Notes
- Two collections are equivalent if they contain the same items, in any order.
- To compare collections for equality, use Is.EqualTo().
- Has.Member uses object equality to find an object in a collection. To check for an object equal to an item the collection, use Has.Some.EqualTo().
- Beginning with NUnit 2.4.2, use of a collection constraint with a non-collection argument causes an error rather than a test failure. This avoids false positives when the collection constraint is negated.
- Beginning with NUnit 2.4.6, you may use any object implementing IEnumerable in place of a collection.
Examples of Use
int[] iarray = new int[] { 1, 2, 3 }; string[] sarray = new string[] { "a", "b", "c" }; Assert.That( iarray, Is.All.Not.Null ); Assert.That( sarray, Is.All.InstanceOfType(typeof(string)) ); Assert.That( iarray, Is.All.GreaterThan(0) ); Assert.That( sarray, Is.Unique ); Assert.That( iarray, List.Contains(3) ); Assert.That( sarray, List.Contains("b") ); Assert.That( sarray, List.Not.Contains("x") ); Assert.That( new string[] { "c", "a", "b" }, Is.EquivalentTo( sarray ) ); Assert.That( new int[] { 1, 2, 2 }, Is.Not.EquivalentTo( iarray ) ); Assert.That( new int[] { 1, 3 }, Is.SubsetOf( iarray ) ); // Using inheritance Expect( iarray, All.GreaterThan( 0 ) ); Expect( sarray, Contains("b") ); Expect( new int[] { 1, 3 }, SubsetOf( iarray ) );