您可以使用自定义
matcher执行此操作.
Warning: Be reasonable with using complicated argument matching, especially custom argument matchers, as it can make the test less readable. Sometimes it’s better to implement equals() for arguments that are passed to mocks (Mockito naturally uses equals() for argument matching). This can make the test cleaner.
public class TypeOrMatcher extends ArgumentMatcher {
private final List> clazzes;
public TypeOrMatcher(Class>...clazzes) {
this.clazzes = new ArrayList>(clazzes);
}
public boolean matches(Object actual) {
if (actual == null) {
return false;
}
Class> actualClass = actual.getClass();
for (Class> clazz : clazzes) {
if (clazz.isAssignableFrom(actualClass) {
return true;
}
}
return false;
}
}
TypeOrMatcher isTypeOneOrTwo = new TypeOrMatcher(
ArgumentType1.class, ArgumentType2.class);
Some mockObj = mock(Some.class);
when(mockObj.someMethod(argThat(isTypeOneOrTwo), any(ArgumentType3.class))
.thenReturn(true);