我使用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
最佳答案
在这条线
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})
关于java - 反射-EasyMock-ClassCastException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19522763/