Home > Net >  Generics and ArgumentCaptor in mockito
Generics and ArgumentCaptor in mockito

Time:11-15

in mockito's verify i want to capture an argument of type Consumer<String>. How should i write the line to avoid type erasure?

I'm reached the this point and it doesn't compile

ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.<Consumer<String>, Consumer<String>>forClass(Consumer<String>.class);

how can i do it?

CodePudding user response:

As stated in the documentation of ArgumentCaptor although this class is generic, it doesn't perform any validation:

This utility class don't do any type checks, the generic signatures are only there to avoid casting in your code.

Hence, if you make use of row types it wouldn't be less type-safe, but there's a drawback - the compiler will issue a warning.

@SuppressWarnings("unchecked")
ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.forClass(Consumer.class);

There's a cleaner option which also mentioned in the documentation linked above, namely to declare the captor as a field and annotate it with @Captor.

@Captor
ArgumentCaptor<Consumer<String>> captor;
  • Related