Java Reference
In-Depth Information
public void
describeTo( Description description ) {
description.appendText("a string that is not null and not empty");
}
D
@Factory
public static
<T> Matcher<String> isNotNullOrEmpty() {
return new
IsNotNullOrEmpty();
}
E
@Factory
public static
<T> Matcher<String> notNullOrEmpty() {
return new
IsNotNullOrEmpty();
}
}
Basically, if we want to create a custom matcher, we need to extend one of the two
classes
BaseMatcher<T>
or
TypeSafeMatcher<T>
. In this listing, we extend the first
one
B
. Next, we override the
matches
method
C
, and we implement our logic on
what occasion the matcher will match the conditions; our condition is matched suc-
cessfully if the string parameter to which it is applied is not
null
and is different from
an empty string.
Here comes the difference between
BaseMatcher<T>
and
TypeSafeMatcher<T>
. As
you'll see later, if you extend
TypeSafeMatcher<T>
, then you'll have to override
another method with the signature
protected boolean matchesSafely(T item);
This means that the method that has to implement our logic can never accept a
null
object. It will always accept a parameter of type
T
, which has already been checked for
null
value and can never be
null
. We want to implement this check, however, so we
stick with the
BaseMatcher<T>
class
.
In
D
we append a description for the matcher. This description is used in our test
cases in case the matcher can't match the condition. In
E
we provide two factory
methods (denoted by the
@Factory
annotation). We call these methods from our test
cases to create an instance of our matcher. We provide two methods, only for readabil-
ity purposes; sometimes it will be more readable to call one of them and sometimes
the other.
Listing B.9 shows the corresponding test class that uses our test methods.
Listing B.9
Test class to demonstrate the
IsNotNullOrEmpty
matcher
[...]
import static
com.manning.junitbook.appD.custom.matchers
.IsNotNullOrEmpty.isNotNullOrEmpty;
import static
com.manning.junitbook.appD.custom.matchers
.IsNotNullOrEmpty.notNullOrEmpty;
B
public class
TestStringIsNullUsingMatcher {
C
@Test(expected=java.lang.AssertionError.
class
)
public void
testIsNotNullOrEmptyButIsNull() {