0

我正在使用模拟 1.7.4。我使用自定义 API 来验证当前服务中的预期行为,我可以通过反编译查看代码。我在此行为验证之上构建了我的逻辑,并且我想对其进行单元测试。验证步骤(基于 API)是:

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

在我的测试环境中,我模拟了 someService.getCustomObject("objectName") 部分,它完美地显示出来。但是,因为模拟对象不包含给定的验证器方法,它会抛出 NoSuchMethodException。

为了解决这个问题,我添加了一个方法对象(比如模拟反射api的方法):

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

因为该对象具有 getClass 方法并且不需要参数,所以它完美地构建了一个方法。之后,我想调用上面的方法(名为 mthd)而不是原始方法,并根据需要更改调用结果(true 或 false):

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

毕竟,它仍然给我 NoSuchMethodException at Mockito.when(co.getClass().getMethod(verifierMethodName,VerifierClass.class)).thenReturn(mthd)

我该如何解决这个问题?

4

0 回答 0