0

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 アクションは単純です。

    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
4

1 に答える 1

1

この行で

method = obj.getClass().getDeclaredMethod(methodName, (Class<?>[]) formalParams);

あなたは を にキャストしObject[]ていClass[]ます。これはうまくいきません。これらのタイプは互換性がありません。

代わりに、formalParamsパラメータを type に変更してくださいClass[]

public static Object genericInvokMethod(Object obj, String methodName, Class[] formalParams, Object[] actualParams) {

そしてそれを呼び出します

genericInvokMethod(cAction, "test1", new Class[]{HttpServletRequest.class}, new Object[]{request})
于 2013-10-22T16:01:52.367 に答える