Skip to content

Collections

When the outcome of your test deals with data stored in a collection, the CollectionAssert class is used.

CollectionAssert Class

The CollectionAssert class contains methods to determine the result of a test where the outcome deals with a collection.

Common Assert Class Method

  • AreEqual(ICollection, ICollection) - Tests whether the specified collections are equal and throws an exception if the two collections are not equal. Equality is defined as having the same elements in the same order and quantity. Whether two elements are the same is checked using Equals(Object, Object) method. Different references to the same value are considered equal.
  • Contains(ICollection, Object) - Tests whether the specified collection contains the specified element and throws an exception if the element is not in the collection.
  • DoesNotContain(ICollection, Object) - Tests whether the specified collection does not contain the specified element and throws an exception if the element is in the collection.

Examples

C#
[TestMethod]
public void GetFruits_ReturnsCopyOfFruits()
{
    // Arrange and Act omitted for this example

    // Assert
    CollectionAssert.AreEqual(fruits, expectedFruits);
}

In this example, fruits is a List containing several strings. The CollectionAssert.AreEqual method checks if items within the expectedFruits list are equal to the items in the fruits list. If any of the items are not the same (order matters) or the lists do not contain the same number of items, the method will raise an AssertFailedException.

C#
[TestMethod]
public void AddFruit_NewFruit_ListContainsElement()
{
    // Arrange and Act omitted for this example

    // Assert
    CollectionAssert.Contains(fruits, expectedFruit);
}

In this example, fruits is a List containing several strings. The CollectionAssert.Contains method checks if expectedFruit is present in the fruits list. If it’s not, the method will raise an AssertFailedException.

C#
[TestMethod]
public void RemoveFruit_FruitToRemove_ListDoesNotContainElement()
{
    // Arrange and Act omitted for this example

    // Assert
    CollectionAssert.DoesNotContains(fruits, expectedFruit);
}

The CollectionAssert.Contains method checks if expectedFruit is not present in the fruits list. If it is, the test will method an AssertFailedException.

Further Reading