Java Reference
In-Depth Information
Using Lambda Expressions in Test Doubles
A pretty common part of writing unit tests is to use test doubles to describe the expected be-
havior of other components of the system. This is useful because unit testing tries to test a
class or method in isolation of the other components of your code base, and test doubles al-
low you to implement this isolation in terms of tests.
NOTE
Even though test doubles are frequently referred to as mocks , actually both stubs and
mocks are types of test double. The difference is that mocks allow you to verify the
code's behavior. The best place to understand more about this is Martin Fowler's article
on the subject.
One of the simplest ways to use lambda expressions in test code is to implement lightweight
stubs. This is really easy and natural to implement if the collaborator to be stubbed is already
a functional interface.
In Behavioral Write Everything Twice , I discussed how to refactor our common domain lo-
gic into a countFeature method that used a lambda expression to implement different
counting behavior. Example 7-14 shows how we might go about unit testing part of its beha-
vior.
Example 7-14. Using a lambda expression as a test double by passing it to countFeature
@Test
public
public void
void canCountFeatures () {
OrderDomain order = new
new OrderDomain ( asList (
newAlbum ( "Exile on Main St." ),
newAlbum ( "Beggars Banquet" ),
newAlbum ( "Aftermath" ),
newAlbum ( "Let it Bleed" )));
assertEquals ( 8 , order . countFeature ( album -> 2 ));
}
The expected behavior is that the countFeature method returns the sum of some number for
each album it's passed. So here I'm passing in four different albums, and the stub in my test
is returning a count of 2 features for each album. I assert that the method returns 8—that is,
Search WWH ::




Custom Search