NUnit Collection Assertions

The basic assertions provided by the NUnit framework can be used for all unit tests. To make unit tests more readable, there are other assertion types that more clearly express the intent of the tests. This article describes the collection assertions.

AllItemsAreNotNull

When a collection must not include any nulls, you can test it with the AllItemsAreNotNull assertion. This fails if one or more null references exist in the provided collection.

The sample test below checks that, when a missing contact is retrieved, a null Person is not added to the cache. This assumes that the RetrieveContact method returns null if an unknown contact is requested from the database.

AllItemsAreInstancesOfType

For collections that can contain multiple types, you might need to check that all of the items in the sequence are of the same, specified type. You can do this with AllItemsAreInstancesOfType. The first argument is the collection to evaluate. The second is the type desired. If any object in the array is null or of a type that is neither the specified type nor a subclass thereof, the assertion fails.

The test below uses the assertion to create an alternative test to that of the previous example. By definition, all of the items in the collection must be of the Person type or one of its subclasses. However, if an item in the cache is null, the test will fail.

AllItemsAreUnique

You might guess that AllItemsAreUnique passes if every value or reference in a collection is unique, and fails where there are duplicates. The test below shows this. Here we are checking that contacts retrieved from the database twice only appear once in the cache.