Java Reference
In-Depth Information
Listing 7.6
A sample method that opens an HTTP connection
[...]
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.IOException;
public class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try {
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoInput(true);
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();
}
}
If an error occurs, we return null . Admittedly, this isn't the best possible error-
handling solution, but it's good enough for the moment. (And our tests will give
us the courage to refactor later.)
Open an HTTP
connection
Read all
contents
7.4.3
First attempt: easy method refactoring technique
The idea is to be able to test the getContent method independently of a real HTTP
connection to a web server. If you map the knowledge you acquired in section 7.2, it
means writing a mock URL in which the url.openConnection method returns a mock
HttpURLConnection . The MockHttpURLConnection class would provide an implemen-
tation that lets the test decide what the getInputStream method returns. Ideally,
you'd be able to write the following test:
Create a mock
HttpURLConnection
@Test
public void testGetContentOk() throws Exception {
MockHttpURLConnection mockConnection = new MockHttpURLConnection();
mockConnection.setupGetInputStream(
new ByteArrayInputStream("It works".getBytes()));
MockURL mockURL = new MockURL();
mockURL.setupOpenConnection(mockConnection);
WebClient client = new WebClient();
String result = client.getContent(mockURL);
assertEquals("It works", result);
}
Unfortunately, this approach doesn't work! The JDK URL class is a final class, and
no URL interface is available. So much for extensibility. We need to find another
Create a
mock URL
Test the getContent method
Assert the result
 
 
Search WWH ::




Custom Search