Java Reference
In-Depth Information
Figure B.1 The JUnit test runner shows that it takes 4.375 seconds to execute the whole test (with
@Before
and
@After
methods).
B.3
Implementing a custom matcher
As you write more and more tests, you'll see that sometimes it's difficult to read an
assert statement at first glance. For instance, consider this one:
assertTrue( user.getContext().getPassword().size() >= 6
&& containsADigit(user.getContext().getPassword()) );
No matter how familiar you are with the code, you'll always need a few seconds to
understand the assert statement. One way to simplify it is by introducing a new
method (like the
containsADigit
method we added). Another way is to add Ham-
crest matchers; that will greatly simplify the assert statement. But we might use this
assert statement a lot in our tests, and it's very cumbersome to copy and paste the
same long assert everywhere. Wouldn't it be great if there was a way to implement a
custom Hamcrest matcher, so that the assert statement would be simplified?
Fortunately, there is a way, and that's exactly what we show next. We start by imple-
menting a simple matcher that checks whether a given string is
null
or empty. Listing
B.8 shows the code for the matcher.
Listing B.8
Our first Hamcrest matcher implementation
[...]
import
org.hamcrest.BaseMatcher;
import
org.hamcrest.Description;
import
org.hamcrest.Factory;
import
org.hamcrest.Matcher;
B
public class
IsNotNullOrEmpty
extends
BaseMatcher<String> {
C
public boolean
matches( Object string ) {
String str = (String) string;
return
( str != null ) && !str.equals( "" );
}