Java Reference
In-Depth Information
@Test
public void testComparingTwoPoints() throws Exception {
Point p1 = new Point(10, 15);
Point p2 = new Point(10, 20);
int result = Point.compareByXAndThenY.compare(p1 , p2);
assertEquals(-1, result);
}
8.3.2. Focusing on the behavior of the method using a lambda
But the purpose of lambdas is to encapsulate a one-off piece of behavior to be used by another
method. In that case you shouldn't make lambda expressions available publicly; they're only an
implementation detail. Instead, we argue that you should test the behavior of the method that
uses a lambda expression. For example, consider the method moveAllPointsRightBy shown
here:
public static List<Point> moveAllPointsRightBy(List<Point> points, int x){
return points.stream()
.map(p -> new Point(p.getX() + x, p.getY()))
.collect(toList());
}
There's no point (pun intended) in testing the lambda p -> new Point(p.getX() + x, p.getY()); it's
only an implementation detail for the method moveAllPointsRightBy. Rather, you should focus
on testing the behavior of the method moveAllPointsRightBy:
@Test
public void testMoveAllPointsRightBy() throws Exception{
List<Point> points =
Arrays.asList(new Point(5, 5), new Point(10, 5));
List<Point> expectedPoints =
Arrays.asList(new Point(15, 5), new Point(20, 5));
List<Point> newPoints = Point.moveAllPointsRightBy(points, 10);
assertEquals(expectedPoints, newPoints);
}
Note that in the unit test just shown, it's important that the Point class implement the equals
method appropriately; otherwise it will rely on the default implementation from Object!
 
Search WWH ::




Custom Search