Skip to content

Instantly share code, notes, and snippets.

@deckerego
Created December 6, 2013 14:24
Show Gist options
  • Save deckerego/7825450 to your computer and use it in GitHub Desktop.
Save deckerego/7825450 to your computer and use it in GitHub Desktop.
Unit testing a Servlet managed by Spring
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class TestServlet {
private HttpServlet servlet;
@Resource
protected ApplicationContext applicationContext;
@Before
public void initServlet() throws Exception {
StaticWebApplicationContext webContext = new StaticWebApplicationContext();
webContext.setParent(applicationContext);
MockServletContext servletContext = new MockServletContext();
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
MockServletConfig servletConfig = new MockServletConfig(servletContext);
this.servlet = new MyServlet();
this.servlet.init(servletConfig);
}
@Test
public void testRequest() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
this.servlet.doPost(new MockHttpServletRequest(), response);
Assert.assertNotNull(response.getContentAsString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment