【问题标题】:Reflection - EasyMock - ClassCastException反射 - EasyMock - ClassCastException
【发布时间】:2013-10-22 15:57:27
【问题描述】:

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

【问题讨论】:

    标签: java reflection junit easymock


    【解决方案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})
    

    【讨论】:

    • 成功了!非常感谢你让我直截了当。你摇滚!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多