2013-10-22 56 views
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 

回答

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}) 
+0

這工作!非常感謝你爲我設置直線。你搖滾! – ogottwald