MockServletBase.java

From Null-pointer

Jump to: navigation, search

Helpful base class for testing controllers

package null-pointer.servlet;
 
import null-pointer.servlet.MyAutoWiredObject;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.DispatcherServlet;
 
/**
 * @author Paul Kane
 * @since 14-Jul-2010
 */
public class MockServletBase {
 
    protected static final String JSP_PREFIX = "/WEB-INF/jsp/";
    protected static final String JSP_SUFFIX = ".jsp";
    protected static DispatcherServlet ds;
    protected static MockServletConfig servletConfig;
 
    protected MyAutoWiredObject myAutoWiredObjectMock;
 
    public void setUp() throws Exception {
        MockServletContext msc = new MockServletContext();
 
        servletConfig = new MockServletConfig(msc);
        ds = new DispatcherServlet();
        ds.setNamespace("applicationContext-test");
        ds.init(servletConfig);
        ApplicationContext applicationContext =  ds.getWebApplicationContext();
        myAutoWiredObjectMock = (MyAutoWiredObject) applicationContext.getBean("myAutoWiredObject");
    }
 
    public void tearDown() throws Exception {
 
    }
 
    public MockHttpServletResponse service(String method, String path) throws Exception {
        return service(null, method, path);
    }
 
    public MockHttpServletResponse service(MockHttpServletRequest request) throws Exception {
        return service(request, null, null);
    }
 
    private MockHttpServletResponse service(MockHttpServletRequest request, String method, String path) throws Exception
    {
        if ( request == null ) {
            request = new MockHttpServletRequest(method, path);
        }
        MockHttpServletResponse response = new MockHttpServletResponse();
        ds.service(request, response);
//        String body = response.getContentAsString();
//        System.out.println("body[" + body + "]");
        return response;
    }
 
 
    protected static String getForwardUrl(String path) {
        return JSP_PREFIX + path + JSP_SUFFIX;
    }
}
Personal tools