Server Rule

A JUnit rule that starts and stops a web server.

Get Server Rule

Example

We write a test that checks the status code for a single URL. The rule delivers all files from the directory src/test/webapp. Hence we add a single file our_file.htmlto this directory.

src
└──test
   └──webapp
      └──our_file.html

Now we write a test that opens a connection to the URL http://localhost:8080/our_file.html and checks the status code.

public class OurTest {
  @Rule
  public final HttpServer server = new HttpServer();

  @Test
  public void checksStatusCodeOkForOurFile() {
    URL url = new URL("http://localhost:8080/our_file.html");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    assertEquals(200, connection.getResponseCode());
  }
}

Options

HttpServer uses port 8080 by default, but you can specify a different port.

@Rule
public final HttpServer server = new HttpServer().withPort(1234);

That's all for now :-)