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
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With