How to capture a list of specific type with mockito

后端 未结 8 1597
天命终不由人
天命终不由人 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:56

    There is an open issue in Mockito's GitHub about this exact problem.

    I have found a simple workaround that does not force you to use annotations in your tests:

    import org.mockito.ArgumentCaptor;
    import org.mockito.Captor;
    import org.mockito.MockitoAnnotations;
    
    public final class MockitoCaptorExtensions {
    
        public static  ArgumentCaptor captorFor(final CaptorTypeReference argumentTypeReference) {
            return new CaptorContainer().captor;
        }
    
        public static  ArgumentCaptor captorFor(final Class argumentClass) {
            return ArgumentCaptor.forClass(argumentClass);
        }
    
        public interface CaptorTypeReference {
    
            static  CaptorTypeReference genericType() {
                return new CaptorTypeReference() {
                };
            }
    
            default T nullOfGenericType() {
                return null;
            }
    
        }
    
        private static final class CaptorContainer {
    
            @Captor
            private ArgumentCaptor captor;
    
            private CaptorContainer() {
                MockitoAnnotations.initMocks(this);
            }
    
        }
    
    }
    

    What happens here is that we create a new class with the @Captor annotation and inject the captor into it. Then we just extract the captor and return it from our static method.

    In your test you can use it like so:

    ArgumentCaptor>>> fancyCaptor = captorFor(genericType());
    

    Or with syntax that resembles Jackson's TypeReference:

    ArgumentCaptor>>> fancyCaptor = captorFor(
        new CaptorTypeReference>>>() {
        }
    );
    

    It works, because Mockito doesn't actually need any type information (unlike serializers, for example).

提交回复
热议问题