Tuesday Aug 21, 2007

Unit Testing HTTP Calls

I have been working with RESTful web services and had the need to verify the HTTP messages I was sending were appropriate. Since I am doing this work using Java SE 6, I was able to take advantage of the httpserver package. This package provides a lightweight HTTP server and is used for things like publishing web services and displaying memory graphs based on jmap.

The code to take advantage of this is easy. As you can see below, my strategy was to get an arbitrary open port on the local machine, bind a test handler to a context where the message is directed, and then verify what was sent matches what was expected.

 InetSocketAddress address = new InetSocketAddress(0); // get free port on local machine
HttpServer server =HttpServer.create(address, 1); // create a server on the arbitrary port
int portNumber = server.getAddress().getPort(); // get the port where this is bound for the invocation
       
MockHttpHandler handler = new MockHttpHandler(); // create a mock handler to capture the HTTP input
try {
    server.start(); // start the server
    server.createContext("/test",handler); // create a context with the mock handler
 ...
        } finally {
            server.stop(0); // stop the server after the test is complete
        }
About

cwebster

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today