6.031 — Software Construction
Spring 2017

Testing HttpServers

Starting with this server:

public class ExampleServer {
    private final HttpServer server;

    public ExampleServer() throws IOException {
        server = HttpServer.create();
        // etc. etc.
    }
    public void start() {
        server.start();
    }
    public int port() {
        return server.getAddress().getPort();
    }
    public void stop() {
        server.stop(0);
    }
}

We can write tests using the URL class to connect and make GET requests.

public class ExampleServerTest {

    @Test
    public void testValid() throws IOException {
        final ExampleServer server = new ExampleServer();
        server.start();

        final String valid = "http://localhost:" + server.port() + "/hello/world";
        // if a URL might contain non-ASCII characters, we would need to encode it:
        //   new URL(new URI(valid).toASCIIString())
        final URL url = new URL(valid);

        // in this test, we will just assert correctness of the server's output
        final InputStream input = url.openStream();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        assertEquals("greeting", "Hello, world!", reader.readLine());
        assertEquals("end of stream", null, reader.readLine());
        server.stop();
    }

    @Test
    public void testInvalid() throws IOException {
        final ExampleServer server = new ExampleServer();
        server.start();

        final String invalid = "http://localhost:" + server.port() + "/???/!!!";
        // if a URL might contain non-ASCII characters, we would need to encode it:
        //   new URL(new URI(invalid).toASCIIString())
        final URL url = new URL(invalid);

        // in this test, we will just assert correctness of the response code
        // unfortunately, an unsafe cast is required here to go from general
        //   URLConnection to the HTTP-specific HttpURLConnection that will
        //   always be returned when we connect to a "http://" URL
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        assertEquals("response code", 404, connection.getResponseCode());
        server.stop();
    }
}