Spring: Unit Testing

Create a base test class which sets up the WebApplicationContext:

public class WebApplicationContextTest extends TestCase {

    private WebApplicationContext context;

    public void setUp() throws Exception {
        String[] paths =
            { "/WEB-INF/applicationContext.xml",
            "/WEB-INF/action-servlet.xml" };
        context = new XmlWebApplicationContext();
        context.setConfigLocations(paths);
        context.setServletContext(new MockServletContext(""));
        context.refresh();
    }
}

Then you can subclass that and access the controllers easily:

public class UserControllerTest extends WebApplicationContextTest {

    public void testBasicHandle() {
        UserController controller = (UserController)
            getContext().getBean("userController");
        ModelAndView modelAndView =
            controller.handleRequest((HttpServletRequest) null,
            (HttpServletResponse) null);
        Map model = modelAndView.getModel();
        assertNotNull(model.get("users"));
        assertEquals(modelAndView.getViewName(), "userList");
    }
}
public class FindUserFormControllerTest extends WebApplicationContextTest {

    User user; // initialized in setUp

    public void testFindFromId() {
        MockHttpServletRequest request =
            new MockHttpServletRequest("POST", "/findUserByName.html");
        request.addParameter("id", user.getId().toString());
        request.addParameter("find", ""); // button pressed

        FindUserFormController controller = (FindUserFormController)
            getContext().getBean("findUserFormController");
        ModelAndView modelAndView =
            controller.handleRequest(request,
            new MockHttpServletResponse());
        Map model = modelAndView.getModel();

        assertNotNull(model.get("users"));
        assertEquals(modelAndView.getViewName(), "findUserByName");
    }
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply