3

I have a service class with the following method:

void doSomething(List<String> list)

I mock this class and I want to verify that a list which is passed as a parameter has only one element. I do it like this:

verify(myService).doSomething((List<String>) argThat(hasSize(1))))

As you see I have to cast the argument to List<String> otherwise it doesn't get compiled:

incompatible types: inferred type does not conform to upper bound(s)
  inferred: java.util.Collection<? extends java.lang.Object>
  upper bound(s): java.util.List<java.lang.String>,java.lang.Object

Question: How can I verify the call without casting? I want to keep things simple, readable and elegant.

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148

1 Answers1

4

I prefer this solution:

final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);

verify(myService).doSomething(argumentCaptor.capture());

assertThat(argumentCaptor.getValue().size()).isEqualTo(1);
Piotr Rogowski
  • 3,642
  • 19
  • 24
  • Thank you. It worked. I had to rework your code a bit as the way you posted it it doesn't get compiled - it requites `ArgumentCaptor>` and I had to do it this way: https://stackoverflow.com/a/5655702/2065796. I'll accept your answer later if there is no better answer. Although it works it is still quite complex, a code that uses combination of matchers would have been shorter and clearer. – Sasha Shpota Aug 23 '18 at 11:29