Java Reference
In-Depth Information
E
private boolean
containsSpecialSymbol( String str ) {
for
( char ch : str.toCharArray() ) {
if
( ( (int) ch ) <= 47 && ( (int) ch ) >= 33 ) {
return true
;
}
}
return false
;
}
F
public void
describeTo( Description description ) {
description.appendText( "string that contains”
+ "a digit, a special character and is at least 6 symbols" );
}
@Factory
public static
<T> Matcher<String> isStrongPassword() {
return new
IsStrongPassword();
}
G
H
@Factory
public static
<T> Matcher<String> strongPassword() {
return new
IsStrongPassword();
}
}
We start the implementation of our custom matcher by extending the
TypeSafe-
Matcher
class
B
. This is the second way to create a matcher.
In
C
we override the
matchesSafely
method and implement our code logic on
what occasion the matcher should match the condition. In our case, the condition is
that the password be longer than six characters and contain a digit and a special sym-
bol.
D
and
E
are two helper methods that we use to validate the password.
The
matchesSafely
method will never accept a
null
value. If that occurs, the
matcher will throw a
java.lang.AssertionFailedError
exception—something that
we strive for (a password can never be
null
).
The
describeTo
method
F
appends a description for our matcher to show in the
log in case the condition does not match. Next, in
G
and
H
we provide two static
factory methods that construct an instance of our matcher. We provide two meth-
ods instead of one because sometimes it's more readable to use one name rather
than the other.
Let's see our matcher in action! It's time to create a test case and use the
matcher. Listing B.11 shows the code. The results from the execution are shown in
figure B.2.