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

发布于 2024-07-06 13:43:00 字数 426 浏览 9 评论 0原文

我对匹配器比较陌生。 我正在尝试将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴情换悲伤 2024-07-13 13:43:00
assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))

来自 Hamcrest 教程

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

另请参阅 Javadoc

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

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

From Hamcrest tutorial:

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

See also Javadoc.

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

帅的被狗咬 2024-07-13 13:43:00

马科斯是对的,但你还有其他一些选择。 首先,有一个非此即彼的情况:

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

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

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

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

assertThat(result, isIn(theCollection))

另请参阅 Javadoc

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

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.

暮年 2024-07-13 13:43:00

除了 anyOf 之外,您还可以选择任一选项,但它的语法略有不同:

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

In addition to the anyOf, you could also go for the either option, but it has a slightly different syntax:

assertThat(result, either(is(1)).or(is(2)).or(is(3))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文