Java Reference
In-Depth Information
If I were to unit test this code, I would focus on the behavior of the method. For example,
Example 7-9 is a test that if there are multiple words in the stream, they are all converted to
their uppercase equivalents.
Example 7-9. Testing conversion of words to uppercase equivalents
@Test
public
public void
void multipleWordsToUppercase () {
List < String > input = Arrays . asList ( "a" , "b" , "hello" );
List < String > result = Testing . allToUpperCase ( input );
assertEquals ( asList ( "A" , "B" , "HELLO" ), result );
}
Sometimes you want to use a lambda expression that exhibits complex functionality. Perhaps
it has a number of corner cases or a role involving calculating a highly important function in
your domain. You really want to test for behavior specific to that body of code, but it's in a
lambda expression and you've got no way of referencing it.
As an example problem, let's look at a method that is slightly more complex than converting
a list of strings to uppercase. Instead, we'll be converting the first character of a string to up-
percase and leaving the rest as is. If we were to write this using streams and lambda expres-
sions, we might write something like Example 7-10 . Our lambda expression doing the con-
version is at .
Example 7-10. Convert first character of all list elements to uppercase
public
public static
static List < String > elementFirstToUpperCaseLambdas ( List < String > words ) {
return
return words . stream ()
. map ( value -> {
char
char firstChar = Character . toUpperCase ( value . charAt ( 0 ));
return
return firstChar + value . substring ( 1 );
})
. collect ( Collectors .< String > toList ());
}
Should we want to test this, we'd need to fire in a list and test the output for every single ex-
ample we wanted to test. Example 7-11 provides an example of how cumbersome this ap-
proach becomes. Don't worry—there is a solution!
Example 7-11. Testing that in a two-character string, only the first character is converted to
uppercase
@Test
public
public void
void twoLetterStringConvertedToUppercaseLambdas () {
List < String > input = Arrays . asList ( "ab" );
Search WWH ::




Custom Search