Java Reference
In-Depth Information
Unit Testing Lambda Expressions
Unit testing is a method of testing individual chunks of code to ensure that they are be-
having as intended.
Usually, when writing a unit test you call a method in your test code that gets called in your
application. Given some inputs and possibly test doubles, you call these methods to test a
certain behavior happening and then specify the changes you expect to result from this beha-
Lambda expressions pose a slightly different challenge when unit testing code. Because they
don't have a name, it's impossible to directly call them in your test code.
You could choose to copy the body of the lambda expression into your test and then test that
copy, but this approach has the unfortunate side effect of not actually testing the behavior of
your implementation. If you change the implementation code, your test will still pass even
though the implementation is performing a different task.
There are two viable solutions to this problem. The first is to view the lambda expression as
a block of code within its surrounding method. If you take this approach, you should be test-
ing the behavior of the surrounding method, not the lambda expression itself. Let's take look
Example 7-8 , which gives an example method for converting a list of strings into their upper-
case equivalents.
Example 7-8. Converting strings into their uppercase equivalents
public static
static List < String > allToUpperCase ( List < String > words ) {
return words . stream ()
. map ( string -> string . toUpperCase ())
. collect ( Collectors .< String > toList ());
The only thing that the lambda expression in this body of code does is directly call a core
Java method. It's really not worth the effort of testing this lambda expression as an independ-
ent unit of code at all, since the behavior is so simple.
Search WWH ::

Custom Search