I would like to know what would be the best way to do unit testing of a servlet.
Testing internal methods is not a problem as long as they don\'t refer to the servl
I looked at the posted answers and thought that I would post a more complete solution that actually demonstrates how to do the testing using embedded GlassFish and its Apache Maven plugin.
I wrote the complete process up on my blog Using GlassFish 3.1.1 Embedded with JUnit 4.x and HtmlUnit 2.x and placed the complete project for download on Bitbucket here: image-servlet
I was looking at another post on an image servlet for JSP/JSF tags just before I saw this question. So I combined the solution I used from the other post with a complete unit tested version for this post.
Apache Maven has a well defined lifecycle that includes test
. I will use this along with another lifecycle called integration-test
to implement my solution.
integration-test
as part of the executions of the surefire-pluginintegration-test
lifecycle.Add this plugin as part of the
.
org.glassfish
maven-embedded-glassfish-plugin
3.1.1
target/${project.build.finalName}
8080
test
true
start
pre-integration-test
start
deploy
stop
post-integration-test
undeploy
stop
Add/modify the plugin as part of the
.
org.apache.maven.plugins
maven-surefire-plugin
2.12.4
true
integration-test
test
false
Add integration tests like the example below.
@Test
public void badRequest() throws IOException {
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setPrintContentOnFailingStatusCode(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/test/images/");
final WebResponse response = page.getWebResponse();
assertEquals(400, response.getStatusCode());
assertEquals("An image name is required.", response.getStatusMessage());
webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(true);
webClient.closeAllWindows();
}
I wrote the complete process up on my blog Using GlassFish 3.1.1 Embedded with JUnit 4.x and HtmlUnit 2.x and placed the complete project for download on Bitbucket here: image-servlet
If you have any questions, please leave a comment. I think that this is one complete example for you to use as the basis of any testing you are planning for servlets.