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?");
}
}
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.
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.
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.
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.
Most likely this is the startsWith
method from the Hamcrest org.hamcrest.Matchers
class.
import static org.hamcrest.core.StringStartsWith.startsWith;
enables both
assertThat(msg, startsWith ("what"));
and
ExpectedException.none().expectMessage(startsWith("What")); //HERE
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