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...AllItemsConstraint( Constraint )applies a constraint to each item in a collection
Is.UniqueUniqueItemsConstraint()tests that a collection contains only unique items
List.Contains( 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().

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