Created
December 6, 2013 14:24
-
-
Save deckerego/7825450 to your computer and use it in GitHub Desktop.
Unit testing a Servlet managed by Spring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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