0

I tried everything to get 100% of coverage on this lambda method but no matter what I do I don't get it.

private String createMessage(List<FieldError> erros) {
    return erros.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (keyOld, keyNew) -> keyOld)).toString();
}

IMG1

IMG2

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    I tried a standard set of test cases using your code (empty list, single item, multiple items, items with duplicate keys) and achieved 100% coverage with the coverage tool built in to IntelliJ. I haven't tried with jacoco. It could well be an issue with jacoco's handling of lambdas. Have you tried another tool? – sprinter May 03 '21 at 21:41
  • The only test that I didn't do was duplicate keys. That the only one was missing – Wiliam Junior May 04 '21 at 01:03
  • That optional third argument to `toMap` is specifically to handle merging keys which is why it isn't exercised if you don't test with duplicate keys. – sprinter May 04 '21 at 01:28

1 Answers1

1

The uncovered code is the implementation of a lambda expression. You only have one lambda expression (keyOld, keyNew) -> keyOld, which means that that code doesn't get executed.

The lambda expression is the 3rd argument to Collectors.toMap(), i.e. BinaryOperator<U> mergeFunction, which is documented as "a merge function, used to resolve collisions between values associated with the same key".

If there are no collisions in the data, the lambda expression won't get executed, so make sure you test the code with data where the erros list contains 2 or more elements with the same getField() value.

Andreas
  • 154,647
  • 11
  • 152
  • 247