JUnit / Hamcrest - org.hamcrest.CoreMatchers.is()已被弃用。我应该使用什么替代品?

4

方法org.hamcrest.CoreMatchers.is()已过时。
文档建议使用org.hamcrest.CoreMatchers.isA()代替。

但是,isA()似乎完全针对不同的情况。

好吧,无论如何,回到我的问题。以前我使用以下方式使用is()

// might be i should not be using it like this, but it works.
assertThat(actualRes, is(true));

现在我无法像使用 isA() 一样使用它。它会抛出编译错误,指出参数不适用于布尔值。

我知道 isA() 的作用。但是我想知道的是,既然 is() 已经过时了,那么我该使用什么来代替 assertThat(actualRes, is(true))

1个回答

6

CoreMatchers.is()的弃用形式是这个

is(java.lang.Class type)

已弃用。请使用isA(Class type)。

因此,对于这个断言,isA是正确的替代方案,但你在使用这个形式的CoreMatchers.is()assertThat(actualRes, is(true));,它是这个...

is(T value)

一个经常使用的is(equalTo(x))的简写。

... 这个没有弃用

以下是一些可能会澄清问题的代码:

boolean actualRes = true;

// this passes because the *value of* actualRes is true
assertThat(actualRes, CoreMatchers.is(true));

// this matcher is deprecated but the assertion still passes because the *type of* actualRes is a Boolean
assertThat(actualRes, CoreMatchers.is(Boolean.class));

// this passes because the *type of* actualRes is a Boolean
assertThat(actualRes, CoreMatchers.isA(Boolean.class));

感谢您的回答。但不幸的是,http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#is(java.lang.Class) 也被弃用了。我现在快要疯了,有没有其他建议可以帮助我? :-) - samshers
@samshers 我已经更新了我的答案,简而言之; 这个方法:is(java.lang.Class<T> type) 已经被弃用,但是你在这个断言中没有使用那个方法:assertThat(actualRes, Matchers.is(true)); - glytching
太棒了,我明白了。谢谢。 - samshers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接