Java Reference
In-Depth Information
6.3.2
Testing for failure conditions
Now that you have the first test working, let's see how to test for server failure condi-
tions. The WebClient.getContent(URL) method returns a null value when a failure
occurs. You need to test for this possibility too. With the infrastructure you've put in
place, you need to create a new Jetty Handler class that returns an error code and reg-
ister it in the @Before method of the TestWebClientSetup1 class.
Let's add a test for an invalid URL —a URL pointing to a file that doesn't exist. This
case is quite easy, because Jetty already provides a NotFoundHandler handler class for
that purpose. You only need to modify the TestWebClient setUp method as follows
(changes are in bold):
@BeforeClass
public static void setUp() throws Exception {
Server server = new Server(8080);
TestWebClient t = new TestWebClient();
Context contentOkContext = new Context(server, "/testGetContentOk");
contentOkContext.setHandler(t.new TestGetContentOkHandler());
Context contentNotFoundContext = new Context(server,
" /testGetContentNotFound " );
contentNotFoundContext.setHandler(t.new
TestGetContentNotFoundHandler());
server.start();
}
Here's the code for the TestGetContentNotFoundHandler class:
private class TestGetContentNotFoundHandler extends AbstractHandler {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
Adding a new test in TestWebClient is also a breeze:
@Test
public void testGetContentNotFound() throws Exception {
WebClient client = new WebClient();
String result = client.getContent(new URL(
" http://localhost:8080/testGetContentNotFound"));
assertNull(result);
}
In similar fashion, you can easily add a test to simulate the server having trouble.
Returning a 5xx HTTP response code indicates this problem. To do so, you'll need to
write a Jetty Handler class, using HttpServletResponse.SC_SERVICE_UNAVAILABLE ,
and register it in the @Before method of the TestWebClientSetup1 class.
A test like this would be very difficult to perform if you didn't choose an embed-
ded web server like Jetty.
 
 
 
Search WWH ::




Custom Search