Java Hamcrest 的多个正确结果(是否有或匹配器?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/152714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:58:45  来源:igfitidea点击:

Multiple correct results with Hamcrest (is there an or-matcher?)

javajunithamcrestmatcher

提问by Mo.

I am relatively new to matchers. I am toying around with hamcrestin combination with JUnit and I kinda like it.

我对匹配器比较陌生。我正在将hamcrest与 JUnit 结合使用,我有点喜欢它。

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?

我正在测试的方法返回集合的一个元素。该列表可能包含多个候选。我当前的实现返回第一个命中,但这不是必需的。如果返回任何可能的候选人,我希望我的测试用例成功。你会如何用 Java 表达这一点?

(I am open to hamcrest-alternatives)

(我对 hamcrest 替代品持开放态度)

采纳答案by marcospereira

assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))

From Hamcrest tutorial:

来自Hamcrest 教程

anyOf - matches if any matchers match, short circuits (like Java ||)

anyOf - 如果任何匹配器匹配,则匹配,短路(如 Java ||)

See also Javadoc.

另请参阅Javadoc

Moreover, you could write your own Matcher, what is quite easy to do.

此外,您可以编写自己的 Matcher,这很容易做到。

回答by MatrixFrog

marcos is right, but you have a couple other options as well. First of all, there isan either/or:

marcos 是对的,但您还有其他一些选择。首先,有一个非此即彼/或:

assertThat(result, either(is(1)).or(is(2)));

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:

但如果你有两个以上的项目,它可能会变得笨拙。另外,类型检查器有时会在这样的事情上变得奇怪。对于你的情况,你可以这样做:

assertThat(result, isOneOf(1, 2, 3))

or if you already have your options in an array/Collection:

或者如果您已经在数组/集合中有您的选项:

assertThat(result, isIn(theCollection))

See also Javadoc.

另请参阅Javadoc