When working with collections in unit tests, you'll often need to verify relationships between different sets of data. MSTest's CollectionAssert
class provides powerful methods for testing collection relationships, including IsSubsetOf
and IsNotSubsetOf
. Understanding how these methods can be used is crucial for writing robust unit tests that involves verifying relationships between two sets of data.
Understanding Subset Relationships
A subset is a collection where every element also exists in another collection (the superset). For example, {1, 2}
is a subset of {1, 2, 3, 4, 5}
because both 1 and 2 exist in the larger collection.
Use Case of isSubsetOf
[TestMethod]
public void TestMethod1()
{
var subset = new int[]{ 1, 2, 3 };
var superset = new int[] { 1, 2, 3, 4, 5 };
//This test will pass as all elements in subset exist in superset
CollectionAssert.IsSubsetOf(subset, superset);
}
Use Case of isNotSubsetOf
[TestMethod]
public void TestMethod1()
{
var subset = new int[]{ 1, 2, 9 };
var superset = new int[] { 1, 2, 3, 4, 5 };
// This test passes as element 9 doesn't exist in superset
CollectionAssert.IsNotSubsetOf(subset, superset);
}
Test Failure Scenario for IsSubSetOf
Let's examine this failed test case scenario;
var subset = new int[]{ 1, 2, 9 };
var superset = new int[] { 1, 2, 3, 4, 5 };
//This test will fail because element {9} is not in the superset
CollectionAssert.IsSubsetOf(subset, superset);
Test Failure Scenario for IsNotSubSetOf
Let's examine this failed test case scenario;
[TestMethod]
public void TestMethod1()
{
var subset = new int[]{ 1, 2, 3 };
var superset = new int[] { 1, 2, 3, 4, 5 };
// This test will fail as elements {1, 2, 3} exist in the superset
CollectionAssert.IsNotSubsetOf(subset, superset);
}
When the test case fails, The assertion message is;
CollectionAssert.IsSubsetOf failed.
CollectionAssert.IsNotSubsetOf failed.
Key Considerations
Empty Collections
- An empty collection is considered a subset of any collection
CollectionAssert.IsSubsetOf(new int[] {}, superset)
will always pass
For Example
![Empty Collections]()
Null Values
- Collections containing null values are handled appropriately
{1, null, 2}
can be a subset of {1, 2, 3, null, 4}
For Example
![Null Values]()
Conclusion
Understanding the use of IsSubsetOf
and IsNotSubsetOf
assertions is essential for effective collection testing in MSTest. Remember that these methods test mutually exclusive conditions a collection either is or isn't a subset of another collection. Structure your unit tests to reflect this, and your tests will be more robust and reliable.
Further References