Stephen Agwu
Stephen Agwu

Reputation: 1023

Java Junit Test with Hamcrest: cannot create compositional Matcher

I am new to unit testing in Java and am having a bit of trouble replicating something I performed in a tutorial.

I have an email class which has many properties, but among them is firstName.

private final String firstName;
public String getFirstName() {
        return firstName;
}

The first name is set in the constructor in a standard fashion:

this.firstName = firstName;

I've written a test to test if the email contains a first name. After set up the test looks like this:

@Test
public void emailIsCreated() {
    assertThat(em1, hasProperty("firstName"));
}

This test passes. My problem is that I'm trying to extend the test with a compositional matcher to match the values of the firstname like so:

@Test
public void emailIsCreated() {
    assertThat(em1, hasProperty("firstName", equalTo("Jon")));
}

But I keep getting a compile error that reads:

hasProperty (String) in HasProperty cannot be applied to (String, org.hamcrest.Matcher<java.lang.String>)

My intuition tells me it has a problem with equating the strings based on the message (and the fact that when I successfully preformed this before I was matching an int), but that doesn't seem right... Does anybody know what I'm doing wrong here?

Upvotes: 0

Views: 376

Answers (1)

You are importing hasProperty from the wrong place. HasProperty does not have method with signature (String, org.hamcrest.Matcher<java.lang.String>) as error message shows and as you can double check in the java API doc above.

Matchers on the other hand has both hasProperty methods imported from HasProperty and HasPropertyWithValue.

So the fix is to change the import and use org.hamcrest.Matchers.hasProperty instead of org.hamcrest.beans.HasProperty.hasProperty

Upvotes: 2

Related Questions