How to capture a list of specific type with mockito

后端 未结 8 1587
天命终不由人
天命终不由人 2020-12-12 10:05

Is there a way to capture a list of specific type using mockitos ArgumentCaptore. This doesn\'t work:

ArgumentCaptor> argumen         


        
8条回答
  •  [愿得一人]
    2020-12-12 10:55

    Yeah, this is a general generics problem, not mockito-specific.

    There is no class object for ArrayList, and thus you can't type-safely pass such an object to a method requiring a Class>.

    You can cast the object to the right type:

    Class> listClass =
                  (Class>)(Class)ArrayList.class;
    ArgumentCaptor> argument = ArgumentCaptor.forClass(listClass);
    

    This will give some warnings about unsafe casts, and of course your ArgumentCaptor can't really differentiate between ArrayList and ArrayList without maybe inspecting the elements.

    (As mentioned in the other answer, while this is a general generics problem, there is a Mockito-specific solution for the type-safety problem with the @Captor annotation. It still can't distinguish between an ArrayList and an ArrayList.)

    Edit:

    Take also a look at tenshis comment. You can change the original code from Paŭlo Ebermann to this (much simpler)

    final ArgumentCaptor> listCaptor
            = ArgumentCaptor.forClass((Class) List.class);
    

提交回复
热议问题