我正在尝试在某个已定义的 java 类型的 java .class 对象上模拟 getDeclaredMethod:
AccessRulesMethods accessRulesMock = mock(AccessRulesMethods.class);
Method mockMethod = mock(Method.class);
when(accessRulesMock.getClass().getDeclaredMethod(param.getValue(), String.class, BigInteger.class)).thenReturn(mockMethod);
但我得到以下异常:
java.lang.NoSuchMethodException: myOwnPackage.AccessRulesMethods.methodName(java.lang.String, java.math.BigInteger)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
在第 2130 行进入 java.lang.Class 似乎该方法根本没有被嘲笑。我在这里的另一个讨论中发现这是正确的方法,但没有例子......任何人都知道我怎样才能设法得到我需要的东西?
非常感谢,萨维里奥
商业逻辑:
try {
Method method = AccessRulesMethods.class.getDeclaredMethod(name, String.class, BigInteger.class);
String parameterName = Arrays.asList(method.getParameters()).get(0).getName();
Field inputField = input.getClass().getDeclaredField(parameterName);
inputField.setAccessible(true);
String parameterValueFromInput = (String) inputField.get(input);
AccessRulesMethods accessRulesInstance = beanFactory.getBean(AccessRulesMethods.class);
methodOutput = (MethodOutput) method.invoke(accessRulesInstance, parameterValueFromInput, input.getIdBp());
}catch (InvocationTargetException ite){
throw ite.getTargetException();
}catch (NoSuchMethodException | IllegalAccessException | NoSuchFieldException e) {
throw new CoreApplicationException("Errore tecnico: invocazione metodo fallita", ErrorConstant.getLocalErrorKey(ErrorConstant.LOCAL_ERROR_CODE_ERRVISREFL001), HttpStatus.INTERNAL_SERVER_ERROR);
}
我有一个带有一些方法的 bean:AccessRulesMethod。我从数据库中的表中获取方法名称,并以给定的顺序通过反射调用此方法。为了调用这些方法,首先我得到所需参数的名称(第二个是固定的),然后我将这个参数从输入传递到 API,同样使用反射