Question

I was browsing the junit ExpectedExceptions' javadoc and I can't understand where the startsWith in their example comes from (marked HERE in the code). I checked the CoreMatcher utility class but could not find any static startsWith method.

Where is that method located?

(I can obviously write it myself but that's not the point)

public static class HasExpectedException {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsNullPointerExceptionWithMessage() {
        thrown.expect(NullPointerException.class);
        thrown.expectMessage("happened?");
        thrown.expectMessage(startsWith("What")); //HERE
        throw new NullPointerException("What happened?");
    }
}
Was it helpful?

Solution

Most likely this is the startsWith method from the Hamcrest org.hamcrest.Matchers class.

OTHER TIPS

import static org.hamcrest.core.StringStartsWith.startsWith;

enables both

assertThat(msg, startsWith ("what"));

and

ExpectedException.none().expectMessage(startsWith("What")); //HERE

Looking at ExpectedException, we can see that there are two expectMessage methods defined, one String and one Matcher, which is indeed org.hamcrest.Matcher.

/**
 * Adds to the list of requirements for any thrown exception that it should
 * <em>contain</em> string {@code substring}
 */
public void expectMessage(String substring) {
    expectMessage(containsString(substring));
}

/**
 * Adds {@code matcher} to the list of requirements for the message returned
 * from any thrown exception.
 */
public void expectMessage(Matcher<String> matcher) {
    expect(hasMessage(matcher));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top