Java Reference
In-Depth Information
Figure 6.2
Adding a test case and replacing the real web resource with a stub
Let's look at a stub in action using the simple
HTTP
connection example. Listing 6.1
from the example application demonstrates a code snippet opening an
HTTP
connec-
tion to a given
URL
and reading the content found at that
URL
. Imagine the method is
one part of a bigger application that you want to unit test.
Listing 6.1
Sample method opening 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();
byte
[] buffer =
new
byte
[2048];
int
count;
while
(-1 != (count = is.read(buffer))) {
content.append(
new
String(buffer, 0, count));
}
}
catch
(IOException e) {
return
null
;
}
B
C
D