PDA

View Full Version : Unit testing a Struts Action with Spring integration



dekker
Aug 25th, 2004, 10:14 PM
Hi,
Are there any resources to help me unit test a Struts action that uses Spring beans? I am using the MockStrutsTestCase to test the action but when I insert the code into the action which retrieves beans from the WebApplicationContext, the Unit test fails. Any help would be much appreciated.

Thanks.

-Ed

irbouho
Aug 26th, 2004, 08:46 AM
I use the following class when testing my Struts Actions using Struts Testcase


public abstract class BaseDynamicSpringStrutsTest extends MockStrutsTestCase {

protected StaticWebApplicationContext wac = null;

/**
* getter for WebApplicationContext.
*/
protected StaticWebApplicationContext getWebApplicationContext() {
return this.wac;
}

/**
* finalize the initialization of the WebApplicationContext.
*/
public void finalizeSetUp() {
//bind the WebApplicationContext to the servletContext
ServletContext sc = getActionServlet().getServletContext();
wac.setServletContext(sc);

wac.refresh();
sc.setAttribute(StaticWebApplicationContext.ROOT_W EB_APPLICATION_CONTEXT_ATTRIBUTE, this.wac);
}

protected void setUp() throws Exception {
super.setUp();
setInitParameter("validating", "false");
wac = new StaticWebApplicationContext();
}

protected void tearDown() throws Exception {
wac = null;
super.tearDown();
}
}

If designed the class to use dynamically created StaticWebApplicationContext :lol:. This way I can register new beans dynamically into the WebApplicationContext. You can easily refactor the class to use a static applicationContext.xml

irbouho
Aug 26th, 2004, 08:55 AM
sample usecase:


public class PasswordActionTestSuite extends BaseDynamicSpringStrutsTest {

protected void setUp() throws Exception {
//call parent setUp
super.setUp();

//create sample data
List users = DomainUtils.populateUsers();
List groups = DomainUtils.populateGroups();

//retreive Spring WebApplicationContext and register userManager within Spring WebApplicationContext
MutablePropertyValues pvs = new MutablePropertyValues ();
pvs.addPropertyValue("users", users);
pvs.addPropertyValue("groups", groups);

wac.registerSingleton("userManager", MockUserManager.class, pvs);

//ask parent class to finalize the setup
finalizeSetUp();
}

protected void tearDown() throws Exception {
super.tearDown();
}

public void testEditForm() {
//redirect to editPassword
setRequestPathInfo("/password.do");

//populate form
addRequestParameter("action", "editForm");
addRequestParameter("id", "1");
addRequestParameter("page", "0");

//perform the action
actionPerform();

//verify that the action forwards to "tiles.passwordForm"
verifyTilesForward("editForm", "tiles.passwordForm");

//verify exceptions
verifyNoActionErrors();
}
}

HTH