使用 Mockito 模拟 java.lang.Class getDeclaredMethod(String name, ...Class args) 不起作用

问题描述

我试图在某个定义的 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,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,同样使用反射

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)