Java Reference
In-Depth Information
@After
public void tearDown() {
// Stop Jetty.
}
@Test
public void testGetContentOk() throws Exception {
WebClient client = new WebClient();
String result = client.getContent( new URL(
" http://localhost:8080/testGetContentOk"));
assertEquals ("It works", result);
}
}
In order to implement the @Before and @After methods, you have two options.
You can prepare a static page containing the text "It works" , which you put in the
document root (controlled by the call to context.setResourceBase(String) in list-
ing 6.2). Alternatively, you can configure Jetty to use your own custom Handler that
returns the string "It works" instead of getting it from a file. This is a much more
powerful technique, because it lets you unit test the case when the remote HTTP
server returns an error code to your WebClient client application.
C REATING A J ETTY H ANDLER
Listing 6.4 shows how to create a Jetty Handler that returns the string "It works" .
Listing 6.4
Create a Jetty Handler that returns "It works" when called
private class TestGetContentOkHandler extends AbstractHandler {
@Override
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException {
B
C
D
OutputStream out = response.getOutputStream();
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
writer.write("It works");
writer.flush();
response.setIntHeader(HttpHeaders.CONTENT_LENGTH, writer.size());
writer.writeTo(out);
out.flush();
}
This class creates a handler B by extending the Jetty AbstractHandler class and
implementing a single method, handle . Jetty calls the handle method to forward an
incoming request to our handler. After that, we use the Jetty ByteArrayISO-
8859Writer class C to send back the string "It works" , which we write in the HTTP
response D . The last step is to set the response content length to be the length of the
string written to the output stream (this is required by Jetty) and then send the
response E .
Now that this handler is written, you can tell Jetty to use it by calling context.set-
Handler(new TestGetContentOkHandler()) . You're almost ready to run your test.
E
 
Search WWH ::




Custom Search