Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the declaration of JUnit Matcher#startsWith?

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?");
    }
}
like image 710
assylias Avatar asked Oct 20 '12 09:10

assylias


People also ask

What is matchers in JUnit?

Matchers is an external addition to the JUnit framework. Matchers were added by the framework called Hamcrest. JUnit 4.8.2 ships with Hamcrest internally, so you don't have to download it, and add it yourself.

Does Hamcrest matcher assertion work with JUnit?

In this series on unit testing with JUnit, we started with JUnit tests both using Maven and IntelliJ in the first part. In the second part, we learned about assertions, JUnit 4 annotations, and test suites. In this post, we will cover assertThat, a more expressive style of assertion that uses Hamcrest matchers.

How does assertthat () work in JUnit?

The assertThat() method takes an object and a Matcher implementation. It is the Matcher that determines if the test passes or fails. The assertThat() method just takes care of the "plumming" - meaning calling the Matcher with the given object. JUnit (Hamcrest, really) comes with a collection of builtin matchers you can use.

How does the static method matches () work in JUnit?

The static method matches () creates a new matcher and returns it. This matcher is an anonymous subclass of the class BaseMatcher. The JUnit documentation states that you should always extend BasreMatcher rather than implement the Matcher interface yourself. Thus, if new methods are added to Matcher in the future, BaseMatcher can implement them.


2 Answers

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

like image 134
Mark Rotteveel Avatar answered Sep 28 '22 09:09

Mark Rotteveel


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

enables both

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

and

ExpectedException.none().expectMessage(startsWith("What")); //HERE
like image 29
Val Avatar answered Sep 28 '22 10:09

Val