Hamcrest 的多个正确结果(是否有或匹配器?)
我对匹配器比较陌生。 我正在尝试将 hamcrest 与 JUnit 结合使用,我有点喜欢它。
有没有办法表明多项选择之一是正确的?
像
assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest
我正在测试的方法返回集合的一个元素。 该列表可能包含多个候选者。 我当前的实现返回第一个命中,但这不是必需的。 如果返回任何可能的候选者,我希望我的测试用例能够成功。 你会如何用 Java 表达这一点?
(我对 hamcrest 替代品持开放态度)
I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it.
Is there a way, to state that one of multiple choices is correct?
Something like
assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest
The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?
(I am open to hamcrest-alternatives)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 Hamcrest 教程:
另请参阅 Javadoc。
此外,您可以编写自己的 Matcher,这很容易做到。
From Hamcrest tutorial:
See also Javadoc.
Moreover, you could write your own Matcher, which is quite easy to do.
马科斯是对的,但你还有其他一些选择。 首先,有一个非此即彼的情况:
但如果你有两个以上的项目,它可能会变得笨拙。 另外,类型检查器有时会对这样的事情感到奇怪。 对于您的情况,您可以这样做:
或者如果您已经在数组/集合中拥有选项:
另请参阅 Javadoc。
marcos is right, but you have a couple other options as well. First of all, there is an either/or:
but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do:
or if you already have your options in an array/Collection:
See also Javadoc.
除了
anyOf
之外,您还可以选择任一选项,但它的语法略有不同:In addition to the
anyOf
, you could also go for the either option, but it has a slightly different syntax: