我有一个间谍或模拟对象,我想验证方法是否已被调用 问题,我在执行时收到methodname而不是编译时间
我想做点什么:
SimpleObj mockObject= Mockito.mock(SimpleObj.class);
Class myClass = SimpleObj.class;
Method meth = myClass.getMethod("getGuid");
Mockito.verify(meth.invoke(mockObject));
我使用
做了一种解决方法MockingDetails mockingDetails = Mockito.mockingDetails(mockObject);
Collection<Invocation> invocations = mockingDetails.getInvocations();
List<String> methodsCalled = new ArrayList<>();
for (Invocation anInvocation : invocations) {
methodsCalled.add(anInvocation.getMethod().getName());
}
assertTrue(methodsCalled.contains("getGuid");
问题一直有效,直到我使用PowerMockito:
对于标准方法,它可以工作,但如果方法是最终的,则mockingDetails.getInvocations()
中不存在该方法
(但即使mockingDetails.getInvocations()
中没有
真正的verify(mock).getGuid()
工作得很好
所以如果你有任何想法/建议,那就很高兴
此致
答案 0 :(得分:0)
我实际上是使用反射来完成这项工作的。我不能使用匹配器,但是我有原始参数。我的测试验证了中间代理和数据转换过程是否调用了真正的实现:
private void assertMethodExecuted(String testName, Object ...params) throws Exception {
assertManagerMethodExecuted(getMethodName(testName), params);
}
private void assertManagerMethodExecuted(String methodName, Object[] params) throws Exception {
MiGRPCManagerImpl manager = Whitebox.getInternalState(server, MiGRPCManagerImpl.class);
Method method = Arrays.stream(manager.getClass().getMethods())
.filter(each -> each.getName().equals(methodName))
.findFirst()
.orElse(null);
MiGRPCManagerImpl verify = Mockito.verify(manager, new VerificationMode() {
@Override
public void verify(VerificationData data) {
assertEquals(1, data.getAllInvocations().size());
data.getAllInvocations().get(0).getMethod().equals(method);
}
@Override
public VerificationMode description(String description) {
return this;
}
});
if (params.length == 0) {
method.invoke(verify);
} else if (params.length == 1) {
method.invoke(verify, params[0]);
} else {
method.invoke(verify, params);
}
}
private String getMethodName(String testName) {
return testName.substring(testName.indexOf("_") + 1, testName.length());
}
一个测试是这样的:
@Test
public void test_disconnectFromGui() throws SecurityException, Exception {
String ip = factory.newInstance(String.class);
String userName = factory.newInstance(String.class);
fixture.disconnectFromGui(userName, ip );
assertMethodExecuted(new Object() {}.getClass().getEnclosingMethod().getName(), userName, ip );
}
答案 1 :(得分:0)
这适用于我使用常规Mockito的方式(我使用它来验证是否调用了android.bluetooth.BluetoothGatt中的隐藏方法“ refresh()”:
private void assertMethodInvoked(@NonNull Object object,
@NonNull String methodName,
@NonNull VerificationMode verificationMode) throws Exception {
final Method method = object.getClass().getDeclaredMethod(methodName);
final Object verify = verify(object, verificationMode);
method.invoke(verify);
}