Stubbing a method that takes Class as parameter with Mockito

后端 未结 3 671
迷失自我
迷失自我 2020-12-29 01:08

There is a generic method that takes a class as parameter and I have problems stubbing it with Mockito. The method looks like this:

public 

        
相关标签:
3条回答
  • 2020-12-29 01:34

    Just in order to complete on the same thread, if someone want to stubb a method that takes a Class as argument, but don't care of the type, or need many type to be stubbed the same way, here is another solution:

    private class AnyClassMatcher extends ArgumentMatcher<Class<?>> {
    
        @Override
        public boolean matches(final Object argument) {
            // We always return true, because we want to acknowledge all class types
            return true;
        }
    
    }
    
    private Class<?> anyClass() {
        return Mockito.argThat(new AnyClassMatcher());
    }
    

    and then call

    Mockito.when(mock.doIt(this.anyClass())).thenCallRealMethod();
    
    0 讨论(0)
  • 2020-12-29 01:38

    The problem is, you cannot mix argument matchers and real arguments in a mocked call. So, rather do this:

    when(serviceValidatorStub.validate(
        any(),
        isA(UserCommentRequestValidator.class),
        eq(UserCommentResponse.class),
        eq(UserCommentError.class))
    ).thenReturn(new UserCommentResponse());
    

    Notice the use of the eq() argument matcher for matching equality.

    see: https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html#eq(T)

    Also, you could use the same() argument matcher for Class<?> types - this matches same identity, like the == Java operator.

    0 讨论(0)
  • 2020-12-29 01:41

    Nice one @Ash. I used your generic class matcher to prepare below. This can be used if we want to prepare mock of a specific Type.(not instance)

    private Class<StreamSource> streamSourceClass() {
        return Mockito.argThat(new ArgumentMatcher<Class<StreamSource>>() {
    
            @Override
            public boolean matches(Object argument) {
                // TODO Auto-generated method stub
                return false;
            }
        });
    }
    

    Usage:

        Mockito.when(restTemplate.getForObject(Mockito.anyString(), 
                **streamSourceClass(),**
                Mockito.anyObject));
    
    0 讨论(0)
提交回复
热议问题