Stubbing a method that takes Class as parameter with Mockito

后端 未结 3 673
迷失自我
迷失自我 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> {
    
        @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();
    

提交回复
热议问题