我有一个使用 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