NUnit 中是否存在 Has-Only-One 约束?
我发现自己最近需要很多这种逻辑:
Assert.That(collection.Items, Has.Member(expected_item));
Assert.That(collection.Items.Count(), Is.EqualTo(1));
我看到 NUnit 提供了 Has.Some
和 Has.All
,但我没有看到类似的东西Has.One
。在没有两个断言的情况下完成此任务的最佳方法是什么?
I'm finding myself needing a lot of this sort of logic lately:
Assert.That(collection.Items, Has.Member(expected_item));
Assert.That(collection.Items.Count(), Is.EqualTo(1));
I see that NUnit offers Has.Some
and Has.All
, but I don't see anything like Has.One
. What's the best way to accomplish this without two asserts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试这样的操作:
Single 将返回集合中唯一的项目,或者如果它不包含 1 个项目,则抛出异常。
我对 NUnit 不太熟悉,所以有人可能会提供一个更好的解决方案,确实使用 NUnit 函数...
编辑:快速搜索后,唯一接近的 NUnit 函数是 Is.EquivalentTo( IEnumerable):
IMO 第一个选项对我来说读起来更好,但后者可能会根据您的喜好给出更好的异常消息。
You could try something like this:
Single will return the only item in the collection, or throw an exception if it doesn't contain exactly 1 item.
I'm not that familiar with NUnit though, so someone might offer a better solution that does use an NUnit function...
EDIT: after a quick search, the only NUnit function that seems to come close is
Is.EquivalentTo(IEnumerable)
:IMO the first option reads better to me, but the latter might give a better exception message depending on your preferences.
我认为验证集合中是否只有一项以及验证条件的最佳方法是执行以下操作:
这就是在失败时获得最佳错误消息的方式。
第二种最佳方法是 @BubbleWrap 的编辑答案,它执行断言工作,但无论您的集合有多个项目还是该项目不是预期的项目,都会出现相同的错误。
I think the best way to verify that there is only one item in the collection, and it verifies the condition is to do something like:
That's how you'd get the best error message in case of failure.
The second best way would be @BubbleWrap's edited answer, which does the assertion job but would get the same error whether your collection has more than one item or the item is not the expected one.
从 NUnit 2.6 开始(不在提出此问题时):
Has.Exactly
“对集合中的每个项目应用约束,如果指定数量的项目成功,则成功。” [1]As of NUnit 2.6 (not around when this question was asked):
Has.Exactly
"Applies a constraint to each item in a collection, succeeding if the specified number of items succeed." [1]为什么
这对你来说还不够呢?
How about
Why it is not suffice for you?
如果 Items 属性有一个索引器,您可以使用
If Items property has an indexer you could use