jeudi 18 février 2021

How to call mock-like reflection api method in unit testing when non-existing method call is made by object?

I am using mockito 1.7.4. I use a custom API to verify intended behavior in my current service, I can see the codes via decompiling. I built my logic on top of this behaviour verification and I want to unit test it. The verification step (which as API based) is:

private static boolean verifySomeBehaviour(String verifierMethodName, VerifierClass vf){
    CustomObject custObj = someService.getCustomObject("objectName");
    Method mthd = custObj.getClass().getMethod(verifierMethodName,VerifierClass.class);
    return mthd.invoke(custObj,vf);
}

In my testing environment, I mocked the someService.getCustomObject("objectName") part and it shows up perfectly. However, because the mock object does not contain given verifier method it throws a NoSuchMethodException.

In order to solve this, I added a method object (like mocking the reflection api's Method):

    Method mthd = null;
    try {
        mthd = co.getClass().getMethod("getClass",null);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

Because the object has getClass method and requires no parameters it perfectly builds a method. After that I want to call above method (named mthd) instead of orijinal one and change the invocation result as I want(true or false):

Mockito.when(co.getClass().getMethod(verifierMethodName,VerifierClass.class)).thenReturn(mthd);
Mockito.when(mthd.invoke(co, vf)).thenReturn(true);

Afterall that, it still gives me NoSuchMethodException at Mockito.when(co.getClass().getMethod(verifierMethodName,VerifierClass.class)).thenReturn(mthd).

How can I resolve this problem?





Aucun commentaire:

Enregistrer un commentaire