Legacy Documentation. View NUnit 3 Documentation

Collection Constraints (NUnit 2.4)

Collection constraints perform tests that are specific to collections. The following collection constraints are provided.

Syntax HelperConstructorOperation
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.UniqueUniqueItemsConstraint()tests that a collection contains only unique items
Has.Member( object )CollectionContainsConstraint( object )tests that a collection contains an object
Is.EquivalentTo( ICollection )CollectionEquivalentConstraint( ICollection )tests that two collections are equivalent
Is.SubsetOf( ICollection )CollectionSubsetConstraint( ICollection )tests that one collection is a subset of another

Notes

  1. Two collections are equivalent if they contain the same items, in any order.
  2. To compare collections for equality, use Is.EqualTo().
  3. 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().
  4. 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.

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 ) );