Java Reference
In-Depth Information
6.4.2
Creating a JDK HttpURLConnection stub
The last step is to create a stub implementation of the HttpURLConnection class so you
can return any value you want for the test. Listing 6.7 shows a simple implementation
that returns the string "It works" as a stream to the caller.
Listing 6.7
Stubbed HttpURLConnection class
[...]
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
public class StubHttpURLConnection extends HttpURLConnection {
private boolean isInput = true ;
protected StubHttpURLConnection(URL url) {
super (url);
}
public InputStream getInputStream() throws IOException {
if (!isInput) {
throw new ProtocolException(
"Cannot read from URLConnection"
+ " if doInput=false (call setDoInput(true))");
}
ByteArrayInputStream bais = new ByteArrayInputStream(
new String("It works").getBytes());
return bais;
}
public void disconnect() {}
public void connect() throws IOException {}
public boolean usingProxy() {
return false ;
}
}
HttpURLConnection is an abstract public class that doesn't implement an interface,
so you extend it and override the methods wanted by the stub. In this stub, you
provide an implementation for the getInputStream method because it's the only
method used by your code under test. Should the code to test use more API s from
HttpURLConnection , you'd need to stub these additional methods. This is where the
code would become more complex—you'd need to reproduce completely the same
behavior as the real HttpURLConnection . For example, at B , you test that if set-
DoInput(false) has been called in the code under test, then a call to the get-
InputStream method returns a ProtocolException . (This is the behavior of
HttpURLConnection .) Fortunately, in most cases, you need to stub only a few meth-
ods and not the whole API .
B
 
 
 
Search WWH ::




Custom Search