Java Reference
In-Depth Information
8.3.3. Pulling complex lambdas into separate methods
Perhaps you come across a really complicated lambda expression that contains a lot of logic (for
example, a technical pricing algorithm with corner cases). What do you do, because you can't
refer to the lambda expression inside your test? One strategy is to convert the lambda
expression into a method reference (which involves declaring a new regular method), as we
explained earlier in section 8.1.3 . You can then test the behavior of the new method in your test
as you would with any regular method.
8.3.4. Testing high-order functions
Methods that take a function as argument or return another function (so-called higher-order
functions, explained more in chapter 14 ) are a little harder to deal with. One thing you can do if
a method takes a lambda as argument is test its behavior with different lambdas. For example,
you can test the filter method created in chapter 2 with different predicates:
@Test
public void testFilter() throws Exception{
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<Integer> even = filter(numbers, i -> i % 2 == 0);
List<Integer> smallerThanThree = filter(numbers, i -> i < 3);
assertEquals(Arrays.asList(2, 4), even);
assertEquals(Arrays.asList(1, 2), smallerThanThree);
}
What if the method that needs to be tested returns another function? You can test the behavior
of that function by treating it as an instance of a functional interface, as we showed earlier with a
Comparator.
Unfortunately, not everything works the first time, and your tests may report some errors
related to your use of lambda expressions. So we now turn to debugging!
8.4. Debugging
There are two main old-school weapons in a developer's arsenal to debug problematic code:
Examining the stack trace
Logging
 
Search WWH ::




Custom Search