Java Reference
In-Depth Information
solution and, potentially, another object to mock. One solution is to stub the URL-
StreamHandlerFactory class. We explored this solution in chapter 6, so let's find a
technique that uses mock objects: refactoring the getContent method. If you think
about it, this method does two things: it gets an HttpURLConnection object and
then reads the content from it. Refactoring leads to the class shown in listing 7.7
(changes from listing 7.6 are in bold). We've extracted the part that retrieved the
HttpURLConnection object.
Listing 7.7
Extracting retrieval of the connection object from getContent
public class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try {
HttpURLConnection connection = createHttpURLConnection(url);
InputStream is = connection.getInputStream();
int count;
while (-1 != (count = is.read())) {
content.append( new String( Character.toChars( count ) ) );
}
}
catch (IOException e) {
return null;
}
return content.toString();
}
protected HttpURLConnection createHttpURLConnection(URL url)
throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
In the listing, we call createHttpURLConnection B to create the HTTP connection.
How does this solution let us test getContent more effectively? We can now apply a
useful trick, which consists of writing a test helper class that extends the WebClient
class and overrides its createHttpURLConnection method, as follows:
B
Refactoring
private class TestableWebClient extends WebClient {
private HttpURLConnection connection;
public void setHttpURLConnection(HttpURLConnection connection) {
this .connection = connection;
}
public HttpURLConnection createHttpURLConnection(URL url)
throws IOException {
return this .connection;
}
}
In the test, we can call the setHttpURLConnection method, passing it the mock
HttpURLConnection object. The test now becomes the following (differences are
shown in bold):
 
 
Search WWH ::




Custom Search