[英]Call Mockito.verify programmatically
我有一个较大的代码库,其中包含许多装饰器类,这些装饰器类通常将除一种方法之外的所有方法委托给委托 object,即如下所示:
class WrapperThing implements Thing{
private final Thing delegate;
WrapperThing(Thing thing){this.delegate=thing;}
public boolean method1(){ return delegate.method1(); }
public String method2(int arg1, boolean arg2){ return delegate.method2(arg1, arg2); }
// lots more methods here, all delegating to delegate
}
现在我正在为这些包装器创建单元测试,使用 Junit 5 @TestFactory
,调用WrapperThing
上的每个方法,并想验证包装委托上是否有调用,这是一个 Mockito 模拟。
到目前为止,这是我的代码:
private void testMethodDelegation(final Method method) {
D delegate = mock(delegateType);
W wrapper = createWrapper(delegate);
List<Object> args = new ArrayList<>(method.getParameterTypes().length + 1);
args.add(wrapper);
gatherMethodArgs(method, args); // populate args with mocks or default values
try {
method.invoke(args.toArray(new Object[0]));
}catch(Exception e) {
// this is fine, we're just testing the delegation
}
// now comes the verify part
List<Object> mockArgs = new ArrayList<>();
try {
mockArgs.add(verify(delegate));
mockArgs.addAll(nCopies(args.size()-1, any()));
method.invoke(mockArgs.toArray(new Object[0]));
}catch (Exception e) {
throw new IllegalStateException(e);
}
}
当我运行它时,我得到的错误是:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at some.packagename.AbstractDelegateTest.testMethodDelegation(AbstractDelegateTest.java:81)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
我做错了什么,或者如果您不知道确切的方法,是否无法验证方法调用?
问题是我调用 method.invoke() 错误。 我以为格式是method.invoke([target, arg1, ... argn])
,但实际上是method.invoke(target, [arg1, ... argn])
。 这是漫长的一天,我的坏。
此代码有效:
private void testMethodDelegation(final Method method) {
D delegate = mock(delegateType);
W wrapper = createWrapper(delegate);
List<Object> args = new ArrayList<>(method.getParameterTypes().length);
gatherMethodArgs(method, args); // populate args with mocks or default values
try {
method.invoke(wrapper, args.toArray(new Object[0]));
} catch (Exception e) {
// this is fine, we're just testing the delegation
throw new IllegalStateException(e);
}
callVerify(method, delegate);
}
private void callVerify(final Method method, final D delegate) {
// now comes the verify part
List<Object> mockArgs = new ArrayList<>(method.getParameterTypes().length);
try {
D verifyDelegate = verify(delegate);
gatherVerifyArgs(method, mockArgs);
method.invoke(verifyDelegate, mockArgs.toArray(new Object[0]));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private void gatherVerifyArgs(final Method method, final List<Object> args) {
for (Class<?> parameterType : method.getParameterTypes()) {
if (int.class == parameterType) {
args.add(anyInt());
} else if (boolean.class == parameterType) {
args.add(anyBoolean());
} else if (long.class == parameterType) {
args.add(anyLong());
} else if (double.class == parameterType) {
args.add(anyDouble());
} else if (float.class == parameterType) {
args.add(anyFloat());
} else if (String.class == parameterType) {
args.add(anyString());
} else {
args.add(any());
}
}
}
private void gatherMethodArgs(final Method method, final List<Object> args) {
int i = 0;
for (Class<?> type : method.getParameterTypes()) {
try {
if (type == String.class) {
args.add("");
} else if (type.isArray()) {
args.add(Array.newInstance(type.getComponentType(), 0));
} else if (Primitives.allPrimitiveTypes().contains(type)) {
args.add(Defaults.defaultValue(type));
} else if (Primitives.allWrapperTypes().contains(type)) {
args.add(Defaults.defaultValue(Primitives.unwrap(type)));
} else if (type == List.class) {
args.add(ImmutableList.of());
} else if (type == Set.class) {
args.add(ImmutableSet.of());
} else if (type == Map.class) {
args.add(ImmutableMap.of());
} else if (type.getName().startsWith("java.util.")) {
args.add(type.newInstance());
} else {
args.add(mock(type));
}
} catch (Exception e) {
throw new IllegalStateException(
String.format("Error mocking parameter %d (%s) of method %s", i,
method.getGenericParameterTypes()[i], method), e);
}
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.