mockito如何验证使用methodname和反射

Gui*_* B. 7 reflection verify mockito powermock powermockito

我有一个间谍或一个对象的模拟,我想验证一个方法已被调用问题,我在执行时收到methodname时间而不是编译时间

我想做的事情如下:

  SimpleObj mockObject= Mockito.mock(SimpleObj.class);
  Class myClass = SimpleObj.class;
  Method meth = myClass.getMethod("getGuid");

  Mockito.verify(meth.invoke(mockObject));
Run Code Online (Sandbox Code Playgroud)

我已经使用了一种解决方法

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");
Run Code Online (Sandbox Code Playgroud)

问题一直有效,直到我使用PowerMockito:对于标准方法,它可以工作,但如果方法是最终的,那么该方法不存在mockingDetails.getInvocations() (但即使在mockingDetails.getInvocations() 实际verify(mock).getGuid()工作中没有很好地存在)

因此,如果您有任何想法/建议,那将很高兴

问候

edu*_*ayo 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());
}
Run Code Online (Sandbox Code Playgroud)

测试如下:

@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 );
}
Run Code Online (Sandbox Code Playgroud)