我有一个间谍或对象的模拟,我想验证的方法一直呼吁的问题,我收到方法名在执行时没有编译时间
我想这样做:
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()
工作的好方法
所以,如果你有任何想法/建议它会很高兴
问候
我实际使用反射做这项工作。我不能使用的匹配,但我已经得到了原始参数。我的测试验证了中间代理和数据皈依过程调用真正的实现:
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 );
}