断言集合不包含另一个集合中的任何项目

时间:2017-12-13 11:03:21

标签: c# unit-testing nunit assertions

考虑以下代码:

string[] myCollection = { "a", "b", "c", "d" }; 
string[] anotherCollection = { "c", "d" };

我想测试myCollection不包含anotherCollection的任何项目。我怎样才能在NUnit中实现这一目标?

我试过这些:

CollectionAssert.DoesNotContain(anotherCollection, myCollection);
Assert.That(myCollection, Has.No.Member(anotherCollection));

...但问题是这些函数在单个实体上运行,我没有找到任何方法让它们使用数组。

1 个答案:

答案 0 :(得分:0)

要断言集合包含任何的一组项目,我们可以检查另一个集合的交集是否为空使用LINQ:

string[] subject = { "a", "b", "c", "d" };
string[] forbidden = { "c", "d" };

Assert.IsEmpty(subject.Intersect(forbidden)); 
// Or:
Assert.That(subject.Intersect(forbidden), Is.Empty);

上面显示的测试将失败,因为两个集合都包含值"c""d"

如果我们希望测试仅在集合包含所有禁止项目时失败:

Assert.That(subject.Intersect(forbidden), Is.Not.EquivalentTo(forbidden));
// Or:
Assert.That(subject, Is.Not.SupersetOf(forbidden));