Mockito match any class argument

后端 未结 5 2006
忘了有多久
忘了有多久 2020-12-22 18:48

Is there a way to match any class argument of the below sample routine?

class A {
     public B method(Class a) {}
}

How

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 19:36

    the solution from millhouse is not working anymore with recent version of mockito

    This solution work with java 8 and mockito 2.2.9

    where ArgumentMatcher is an instanceof org.mockito.ArgumentMatcher

    public class ClassOrSubclassMatcher implements ArgumentMatcher> {
    
       private final Class targetClass;
    
        public ClassOrSubclassMatcher(Class targetClass) {
            this.targetClass = targetClass;
        }
    
        @Override
        public boolean matches(Class obj) {
            if (obj != null) {
                if (obj instanceof Class) {
                    return targetClass.isAssignableFrom( obj);
                }
            }
            return false;
        }
    }
    

    And the use

    when(a.method(ArgumentMatchers.argThat(new ClassOrSubclassMatcher<>(A.class)))).thenReturn(b);
    

提交回复
热议问题