[英]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.