Chris Lacy's Software Engineering Blog
Tuesday Jun 22, 2010
Integration Testing Spring Web Applications through DispatcherServlet
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.web.util.WebUtils.*;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.chrislacy.utils.c.EasyEnumeration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class DispatcherTestHelper {
private DispatcherTestHelper() {}
@SuppressWarnings("unchecked")
public static HttpServletResponse test(String configLocation, String method, String path) throws Throwable {
DispatcherServlet ds = new DispatcherServlet();
ds.setContextConfigLocation(configLocation);
ServletConfig sc = mock(ServletConfig.class);
Enumeration e = mock(Enumeration.class);
when(sc.getInitParameterNames()).thenReturn(e);
ServletContext scon = mock(ServletContext.class);
when(scon.getInitParameterNames()).thenReturn(e);
when(scon.getAttributeNames()).thenReturn(e);
when(sc.getServletContext()).thenReturn(scon);
ds.init(sc);
WebApplicationContext wac = ds.getWebApplicationContext();
when(scon.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(wac);
HttpServletRequest hsr = mock(HttpServletRequest.class);
when(hsr.getMethod()).thenReturn(method);
when(hsr.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE)).thenReturn(path);
when(hsr.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE)).thenReturn(path);
when(hsr.getAttribute(INCLUDE_SERVLET_PATH_ATTRIBUTE)).thenReturn(path);
when(hsr.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(wac);
when(hsr.getAttributeNames()).thenReturn(new EasyEnumeration(INCLUDE_REQUEST_URI_ATTRIBUTE,
INCLUDE_CONTEXT_PATH_ATTRIBUTE, INCLUDE_SERVLET_PATH_ATTRIBUTE, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
when(hsr.getRequestURI()).thenReturn(path);
RequestDispatcher rd = mock(RequestDispatcher.class);
when(hsr.getRequestDispatcher(anyString())).thenReturn(rd);
HttpServletResponse hsres = mock(HttpServletResponse.class);
ds.service(hsr, hsres);
verify(rd).include(hsr, hsres);
return hsres;
}
}
@Test
public void test() throws Throwable {
HttpServletResponse hsres = DispatcherTestHelper.test("file:src/main/webapp/WEB-INF/spring/*-config.xml", "GET", "/welcome");
System.out.println(hsres);
}
Posted at 11:32AM Jun 22, 2010 by chris in Java |
Comments: