0
我有EasyMock的JUnit測試。我試圖使用反射將請求傳遞給一個私有方法。我該怎麼做呢。下面是我的源&輸出:反射 - EasyMock - ClassCastException
@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動作很簡單:
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
這工作!非常感謝你爲我設置直線。你搖滾! – ogottwald