Java Reference
In-Depth Information
String str =
null
;
D
assertThat( str, isNotNullOrEmpty() );
assertThat( str, is( notNullOrEmpty() ) );
}
@Test(expected=java.lang.AssertionError.
class
)
public void
testIsNotNullOrEmptyButIsEmpty() {
String str = "";
assertThat( str, isNotNullOrEmpty() );
assertThat( str, is( notNullOrEmpty() ) );
}
@Test
public void
testIsNotNullOrEmptyIsNotNull() {
String str = "test";
assertThat( str, isNotNullOrEmpty() );
assertThat( str, is( notNullOrEmpty() ) );
}
}
All we need to do is use the static import feature of Java 1.5 and import the matcher
that we want to use
B
. After that, we implement three test methods using the custom
matcher we just implemented. The first two deliberately test failing conditions, and we
denote this with the
expected
parameter of the
@Test
annotation
C
. We also use the
two factory methods
D
, the second one in conjunction with one of the core matchers
of Hamcrest.
Now we demonstrate another example of making a custom matcher, this time by
using
TypeSafeMatcher<T>
. For this case, we implement a custom Hamcrest matcher,
which checks to see if a given password is valid. We consider the password to be valid if
it's longer than six characters, contains a digit, and also contains a special symbol (any
of the following: !, ", #, $, %, &, ', (, ), *, +, -, ., /).
Listing B.10 shows our custom Hamcrest matcher.
Listing B.10
IsStrongPassword
custom matcher
[...]
public class
IsStrongPassword extends TypeSafeMatcher<String> {
@Override
public boolean
matchesSafely( String str ) {
return
containsSpecialSymbol( str )
&& containsDigit( str )
&& str.length() >= 6;
}
B
C
D
private boolean
containsDigit( String str ) {
for
( char ch : str.toCharArray() ) {
if
( Character.isDigit( ch ) ) {
return true
;
}
}
return false
;
}