Consider this code:
string[] myCollection = { "a", "b", "c", "d" };
string[] anotherCollection = { "c", "d" };
I want to test that myCollection
does not contain any item of anotherCollection
. How can I achieve that in NUnit?
I tried these:
CollectionAssert.DoesNotContain(anotherCollection, myCollection);
Assert.That(myCollection, Has.No.Member(anotherCollection));
...but the problem is that these functions operate on a single entity and I did not find any way to let them work with arrays.
To assert that a collection does not contain any of a set of items, we can check that the intersection of another collection is empty using LINQ:
string[] subject = { "a", "b", "c", "d" };
string[] forbidden = { "c", "d" };
Assert.IsEmpty(subject.Intersect(forbidden));
// Or:
Assert.That(subject.Intersect(forbidden), Is.Empty);
The test shown above will fail because both collections contain the values "c"
and "d"
.
If we want the test to fail only when the collection contains all of the prohibited items:
Assert.That(subject.Intersect(forbidden), Is.Not.EquivalentTo(forbidden));
// Or:
Assert.That(subject, Is.Not.SupersetOf(forbidden));