Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest assertThat ambiguous?

I got some samplecode from a college, imported the project and try to run the Tests: The method assertThat(Integer, Matcher) is ambiguous for the type MyClass

Every assertThat is marked red with the same error-message so i tried to write the simpliest test which describes the problem:

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

@Test
public void whenAssertThatThenItIsAmbiguous() {
    List<String> list = Arrays.asList("A", "B", "C");
    assertThat(list.size(), is(3));
}

after I scroll over assertThat I get the following message:

The method assertThat(Integer, Matcher<Integer>) is ambiguous for the type MyClass

I searched google and stackoverflow but couldn't find anybody with the same problem... Please help.

EDIT1:

Solution:

import static org.junit.Assert.*; // delete this line

like image 587
MartinL Avatar asked Oct 31 '11 14:10

MartinL


People also ask

What can I use instead of assertThat?

assertThat method defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library. This rule finds the deprecated usages of Assert. assertThat and automatically replaces them with MatcherAssert.

Is Hamcrest deprecated?

It's not deprecated, I always prefer is() to equalTo() for booleans. But they're aliases for each other. You can include * instead of naming each matcher for brevity and to avoid the warning.

Why we use TestNG instead of Hamcrest?

Hamcrest vs TestNG TestNG is a testing framework, and as noted above, Hamcrest is a matcher framework. Both frameworks allow us to make assertions; it is here where Hamcrest does a better job than TestNG. TestNG is a testing framework, and as noted above, Hamcrest is a matcher framework.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.


2 Answers

Both org.junit.Assert and org.hamcrest.MatcherAssert declare assertThat(T, Matcher<T>). Choose to static-import one or the other, but not both, and you should be OK.

like image 121
pholser Avatar answered Oct 04 '22 18:10

pholser


There's two general causes for this, unqualified static imports (import static blah.*), or multiple versions of hamcrest on the path.

You may be able to get around it by using the long-form is(equalTo(3)) (kind of doubt it), culling your static imports, etc.

Which framework you're using it with can matter, too.

like image 37
Dave Newton Avatar answered Oct 04 '22 18:10

Dave Newton