58

I use the following code at the moment to assert on a boolean value, however the method org.hamcrest.Matchers.is() is deprecated.

assertThat(someValue, is(false));

Is there a simple alternative syntax to test for boolean values without resorting to assertTrue() which gives you poor failure messages like "java.lang.AssertionError"


Edit after receiving comments/answers

My initial concerns were raised because Eclipse shows the following import statement as deprecated

enter image description here

On viewing the Hamcrest API docs there are 3 overloaded variations of the is() method, only one of which is deprecated.

Therefore, to clarify the comment from @mark and the answer from @matt, the use of is() that I have posted above is valid and not deprecated.

Brad
  • 15,186
  • 11
  • 60
  • 74

5 Answers5

52

Have you tried equalTo(T)?

assertThat(someValue, equalTo(false));

I don't see that is(T) is deprecated - is(Class) is deprecated however.

matt b
  • 138,234
  • 66
  • 282
  • 345
  • 8
    Thanks for the clarification. You are right `is(T)` is not deprecated. I see that it's overloaded sibling `is(Class)` is deprecated which was leading me to believe that all uses of `is()` were deprecated. – Brad Sep 27 '12 at 07:52
10

I had thought this was a transitive dependency issue, but it's really just a display issue in Eclipse where it marks the import as deprecated because one overloaded form is. The code should compile fine since the import will expose all forms.

The deprecated form has been removed from the source and will not exist in the next release (1.4).

Original Answer

The problem is that JUnit includes a set of Hamcrest classes in its JAR. You can use junit-dep.jar for now, but newer versions (4.9 and 4.10 so far) of JUnit omit them.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • That is a problem but how is it related to this question? I use junit-4.11 and I still get this. In hamcrest-1.3 all three methods mentioned exist. The one that is first in the order eclipse finds them is the deprecated one and AFAICT that is the one eclipse flags as deprecated. Interestingly it is placed below the others in the source file. – aron Aug 07 '14 at 11:24
  • 2
    @aron I've updated my answer now that I see it's just an Eclipse display issue. – David Harkness Aug 07 '14 at 20:43
4

This is deprecated:

import static org.junit.Assert.assertThat;

We can use this instead:

import static org.hamcrest.MatcherAssert.assertThat;
Zain
  • 37,492
  • 7
  • 60
  • 84
N-RAYAN
  • 123
  • 1
  • 1
  • 8
3

It is said, use instanceOf for class matcher in the document.

http://junit.org/javadoc/latest/org/hamcrest/core/Is.html#isA(java.lang.Class)

is(IOException.class);

will be

is(instanceOf(IOException.class));

for example.

shinpei
  • 393
  • 1
  • 4
  • 15
1

This is what worked for me in Jan 2022

import static org.hamcrest.CoreMatchers.*;
Anand Rockzz
  • 6,072
  • 5
  • 64
  • 71