Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't compile hamcrest hasKey() method

This is the code:

Map<Foo, String> map;
org.hamcrest.MatcherAssert.assertThat(map, 
  org.hamcrest.Matchers.hasKey(new Foo()));

This is what compiler is saying:

cannot find symbol method assertThat(java.util.Map<Foo,java.lang.String>,
org.hamcrest.Matcher<java.util.Map<Foo,java.lang.Object>>)

Why and what can I do?

like image 992
yegor256 Avatar asked Jul 28 '11 21:07

yegor256


People also ask

How do I use hamcrest in eclipse?

Including HamcrestRight click on your eclipse project and select 'Properties' and then select 'Java Build Path' in the left pane and 'Libraries' on the right. On the 'Libraries' tab click the 'Add External Jars' button and navigate to the hamcrest-all jar you previously downloaded.

How do you use hamcrest in Testng?

Hamcrest can also be used with mock objects frameworks by using adaptors to bridge from the mock objects framework's concept of a matcher to a Hamcrest matcher. For example, JMock 1's constraints are Hamcrest's matchers. Hamcrest provides a JMock 1 adaptor to allow you to use Hamcrest matchers in your JMock 1 tests.

How do I add hamcrest to IntelliJ?

How to add hamcrest methods into your project by IntelliJ as shown below. For example, we are writing a JUnit test with hamcrest “Is” method. First, click “assertThat” and then press alt+Enter then click “Static Import Method…” Then click “is” and press alt+enter and select “Static Import Method…”


2 Answers

I suspect you need something like:

MatcherAssert.assertThat(map, Matchers.<Foo, String>hasKey());

That way you can specify the value type for the hasKey method call. Looks butt-ugly though, and I'm slightly surprised that type inference doesn't help you...

like image 175
Jon Skeet Avatar answered Oct 25 '22 03:10

Jon Skeet


It sounds like you've hit the same bug that I did. Is this in Hamcrest > 1.1? They changed the generics on their matchers between 1.1 and 1.2. I filed a Hamcrest bug here: http://code.google.com/p/hamcrest/issues/detail?id=143

but it turns out that this is actually a bug in the compiler which can't be fixed in JDK 6 but is already fixed in 7: http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=72ce99618021685c3570069c8f60b?bug_id=7034548

As Jon mentioned, there are a couple of ways to work around it, but they all break the nice, fluent interface of Hamcrest.

like image 37
Ryan Stewart Avatar answered Oct 25 '22 03:10

Ryan Stewart