Gaurav Parek Gaurav Parek - 1 month ago 12
Java Question

Test case for Struts2 2.3.24 using Strut2SpringTestCase (request object is coming as null)

I am trying to write unit test cases for my Struts2 action classes. My Test class extends

SpringStrutsTestCase
class. I am able to set the request object and able to get the action and action is also getting called but when in action it tries to get the parameters set in request object it throws null pointer exception i.e. request object is going as null. Below is my what my test class looks like. Any help is really appreciated.

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;
}
}


Here is my action class.

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";
}
}

Answer

In order to test an action call you need to call execute method of ActionProxy. By calling execute of your action you are just invoking that particular method of the action class and not S2 action along with the interceptors, results, etc.

The correct way would be:

ActionProxy proxy = getActionProxy("/actionName");
proxy.execute();

BTW if you're using JUnit 4 there is StrutsSpringJUnit4TestCase which you should use instead of StrutsSpringTestCase.

Comments