我正在尝试为Struts2操作类编写单元测试用例。我的Test类扩展了SpringStrutsTestCase
类。我能够设置请求对象并且能够获取操作并且操作也被调用但是当它在操作中它试图获取在请求对象中设置的参数时它抛出空指针异常,即请求对象变为空。下面是我的测试类的样子。任何帮助都非常感谢。
import org.apache.struts2.StrutsSpringTestCase;
import org.junit.Test;
import com.opensymphony.xwork2.ActionProxy;
public class testClass extends StrutsSpringTestCase {
@Test
public void test1() throws Exception {
try {
request.setParameter("p1", "v1");
request.setParameter("p2", "v2");
ActionProxy proxy = getActionProxy("/actionName");
MyActionClass loginAction = (MyActionClass) proxy.getAction();
loginAction.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String[] getContextLocations() {
String[] arr = new String[] { "one.xml", "two.xml", "three.xml" };
return arr;
}
}
这是我的动作类。
public class MyAction extends ActionSupport{
private String p1;
private String p2;
/*
Gettere and Setters of p1 and p2
*/
public String execute() throws Exception {
// return "success";
logger.info("Login Action Called");
String pv1= (String) request.getParameter("p1");// If I get value using this.pv1 it works fine but with this code it doesn't.
String pv2= (String) request.getParameter("p2");
return "success";
}
}
答案 0 :(得分:1)
要测试操作调用,您需要调用execute
ActionProxy
方法。通过调用您的操作的execute
,您只是调用动作类的特定方法而不是S2动作以及拦截器,结果等。
正确的方法是:
ActionProxy proxy = getActionProxy("/actionName");
proxy.execute();
顺便说一句,如果您使用的是JUnit 4,则应使用StrutsSpringJUnit4TestCase
代替StrutsSpringTestCase
。