Testing web applications with Jetty

If you’d like to test your web application you might be interested in Jetty: you can deploy your servlets in it, generate HTTP requests and check if certain criteria are met – everything inside a JUnit test.

Jetty has got enough documentation to get you started; if you want more you can get support from the creators of Jetty. This post was inspired by this particular page from the docs. I setup a very small Eclipse project that can be downloaded as tar.gz or zip; alternatively, you can browse the code here.

JUnit scaffolding

Lets have a look at a small JUnit class, that implements a setUp method to bootstrap Jetty:

import org.junit.Before;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
public class WebAppTest {
  private ServletTester tester;
  private HttpTester request;
  private HttpTester response;
  public void setUp() throws Exception {
    this.tester = new ServletTester();
    this.tester.addServlet(MyServlet.class, "/");
    this.request = new HttpTester();
    this.response = new HttpTester();
    this.request.setHeader("Host", "tester");

This method leverages the features provided by the ServletTester class, which will create a Jetty server for us. Instead of writing a web.xml, we can add servlets to the server programmatically. After that we start the server and create a request/response pair that can be used in the test methods.


Now you can write several test methods for every request you’d like to check. If you want to check the start page of your web application you set the URI, generate a request, send it to Jetty, receive the response and check it like so:

  public void testHomepage() throws Exception {
    assertTrue(this.response.getMethod() == null);
    assertEquals(200, this.response.getStatus());
    assertEquals("Hello World", this.response.getContent());

In this simple case the MyServlet class contains a line like this:

  response.getWriter().append("Hello World");


Jetty is said to be highly embeddable. As far as I’ve checked it out, that’s absolutely true. Due to this it’s very easy to use Jetty inside unit tests. I haven’t tried to use Jetty with web frameworks but that should be no problem either. So if you’d like to test your servlets I recommend checking out Jetty.

5 thoughts on “Testing web applications with Jetty”

  1. Pingback: Webservices with Hessian and Burlap

  2. When not moving the mouse the Jetty unit tests take about a minute to start Jetty. Not good for automated scripts. Any idea how to work around this?

Comments are closed.