我有一个使用EasyMock的JUnit测试。我正在尝试使用反射将请求传递给私有方法。我该怎么做呢。以下是我的来源&输出:
@Test
public void testGoToReturnScreen(){
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
expect(request.getParameter("firstName")).andReturn("o");
expect(request.getAttribute("lastName")).andReturn("g");
request.setAttribute("lastName", "g");
replay(request);
CAction cAction = new CAction();
System.out.println("BEFORE");
try {
System.out.println("[1]: "+request);
System.out.println("[2]: "+request.getClass());
System.out.println("[3]: test1 direct call: "+cAction.test1(request));
System.out.println("[4]: test1:"+(String) genericInvokMethod(cAction, "test1", new Object[]{HttpServletRequest.class}, new Object[]{request}));
} catch(Exception e){
System.out.println("e: "+e);
}
System.out.println("AFTER");
}
public static Object genericInvokMethod(Object obj, String methodName, Object[] formalParams, Object[] actualParams) {
Method method;
Object requiredObj = null;
try {
method = obj.getClass().getDeclaredMethod(methodName, (Class<?>[]) formalParams);
method.setAccessible(true);
requiredObj = method.invoke(obj, actualParams);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return requiredObj;
}
Struts Action就是:
private String test1(HttpServletRequest r){
return "test1";
}
在上面的System.out.println命令中,我得到以下输出:
BEFORE
[1]: EasyMock for interface javax.servlet.http.HttpServletRequest
[2]: class $Proxy5
[3]: test1 direct call: test1
e: java.lang.ClassCastException: [Ljava.lang.Object; incompatible with [Ljava.lang.Class;
AFTER
答案 0 :(得分:1)
在这一行
method = obj.getClass().getDeclaredMethod(methodName, (Class<?>[]) formalParams);
您正在向Object[]
投射Class[]
。这不行。这些类型不兼容。
相反,请将formalParams
参数更改为Class[]
类型。
public static Object genericInvokMethod(Object obj, String methodName, Class[] formalParams, Object[] actualParams) {
并将其命名为
genericInvokMethod(cAction, "test1", new Class[]{HttpServletRequest.class}, new Object[]{request})