Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito how to verify using methodname and reflection

I have a spy or a mock of an object and I wants to verify that a method has been call problem, I receive methodname at execution Time not compilation time

I would like to do something like:

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

  Mockito.verify(meth.invoke(mockObject));

I have made a kind of workaround using

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");

Problem it works until I use PowerMockito : for standard method it works but if the method is final, the method is not present in mockingDetails.getInvocations() (but even if not present in mockingDetails.getInvocations() the real verify(mock).getGuid() works in a good way

So if you have any idea/advice it would be glad

Regards

like image 451
Guillaume B. Avatar asked Aug 25 '15 15:08

Guillaume B.


1 Answers

This works for me using regular Mockito (I use this to verify that the hidden method "refresh()" in android.bluetooth.BluetoothGatt is invoked:

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);
}
like image 164
Alix Avatar answered Oct 15 '22 10:10

Alix