我想断言两个列表的元素包含我期望的值,如下所示:
var foundCollection = fooManager.LoadFoo();
var expectedCollection = new List<Foo>()
{
new Foo() { Bar = "a", Bar2 = "b" },
new Foo() { Bar = "c", Bar2 = "d" }
};
//assert: I use AreEquivalent since the order does not matter
CollectionAssert.AreEquivalent(expectedCollection, foundCollection);
然而,上面的代码将无法工作(我猜是因为.Equals()不会为具有相同值的不同对象返回true )。在我的测试中,我只关心公共属性值,而不关心对象是否相等。我可以做些什么来做出我的断言?
发布于 2012-08-29 15:47:15
不是,NUnit目前没有这样的机制。你必须使用你自己的断言逻辑。作为单独的方法,或者利用Has.All.Matches
Assert.That(found, Has.All.Matches<Foo>(f => IsInExpected(f, expected)));
private bool IsInExpected(Foo item, IEnumerable<Foo> expected)
{
var matchedItem = expected.FirstOrDefault(f =>
f.Bar1 == item.Bar1 &&
f.Bar2 == item.Bar2 &&
f.Bar3 == item.Bar3
);
return matchedItem != null;
}
当然,这假设您预先知道所有相关的属性(否则,IsInExpected
将不得不求助于反射),并且元素顺序并不相关。
(你的假设是正确的,NUnit的集合断言对类型使用默认的比较器,在大多数情况下,用户定义的类型将是对象的ReferenceEquals
)
发布于 2012-08-29 14:40:42
你试过这样的东西吗?
Assert.That(expectedCollection, Is.EquivalentTo(foundCollection))
发布于 2014-10-15 19:47:55
我也遇到过类似的问题。列出贡献者,其中包含“评论者”和其他人...我想得到所有的评论,并从中得出创建者,但我只对独特的创建者感兴趣。如果有人创建了50条评论,我只希望她的名字出现一次。因此,我编写了一个测试,以查看评论者是否在GetContributors()结果中。
我可能错了,但我认为你的目标(当我发现这篇文章时我所追求的)是断言在一个集合中每一项都只有一个,在另一个集合中也有。
我这样解决了这个问题:
Assert.IsTrue(commenters.All(c => actual.Count(p => p.Id == c.Id) == 1));
如果您还希望结果列表不包含预期之外的其他项目,则还可以比较列表的长度。
Assert.IsTrue(commenters.length == actual.Count());
我希望这是有帮助的,如果是这样,如果你能给我的答案打分,我将非常感激。
https://stackoverflow.com/questions/12171411
复制相似问题