Java Reference
In-Depth Information
public Point moveRightBy(int x){
return new Point(this.x + x, this.y);
}
}
The following unit test checks whether the method moveRightBy behaves as expected:
@Test
public void testMoveRightBy() throws Exception {
Point p1 = new Point(5, 5);
Point p2 = p1.moveRightBy(10);
assertEquals(15, p2.getX());
assertEquals(5, p2.getY());
}
8.3.1. Testing the behavior of a visible lambda
This works nicely because the method moveRightBy is public. Therefore, it can be tested inside
the test case. But lambdas don't have a name (they're anonymous functions, after all), so it's
trickier to test them in your code because you can't refer to them by a name!
Sometime you may have access to a lambda via a field so you can reuse it, and you'd really like to
test the logic encapsulated in that lambda. What can you do? You could test the lambda just like
when calling methods. For example, let's say you add a static field compareByXAndThenY in the
Point class that gives you access to a Comparator object that's generated from method
references:
public class Point{
public final static Comparator<Point> compareByXAndThenY =
comparing(Point::getX).thenComparing(Point::getY);
...
}
Remember that lambda expressions generate an instance of a functional interface. As a result,
you can test the behavior of that instance. Here, you can now call the method compare on the
Comparator object compareByXAndThenY with different arguments to test that its behavior is
as intended:
 
Search WWH ::




Custom Search