Java Reference
In-Depth Information
The idea is to call the URL static method setURLStreamHandlerFactory in the JU nit
setUp method. (A better implementation would use a TestSetup class, such that this
is performed only once during the whole test suite execution.)
Listing 6.6
Providing custom stream handler classes for testing
[...]
import java.net.URL;
import java.net.URLStreamHandlerFactory;
import java.net.URLStreamHandler;
import java.net.URLConnection;
import java.io.IOException;
public class TestWebClient1 {
@BeforeClass
public static void setUp() {
TestWebClient1 t = new TestWebClient1();
URL.setURLStreamHandlerFactory(t. new StubStreamHandlerFactory());
}
private class StubStreamHandlerFactory implements
URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
return new StubHttpURLStreamHandler();
}
}
private class StubHttpURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(URL url)
throws IOException {
return new StubHttpURLConnection(url);
}
}
@Test
public void testGetContentOk() throws Exception {
WebClient client = new WebClient();
String result = client.getContent( new URL(" http://localhost"));
assertEquals("It works", result);
}
}
We use several (inner) classes ( C and D ) to be able to use the StubHttpURL-
Connection class. We start by calling setURLStreamHandlerFactory B with our first
stub class, StubStreamHandlerFactory . In StubStreamHandlerFactory , we override
the createURLStreamHandler method C , in which we return a new instance of our sec-
ond private stub class, StubHttpURLStreamHandler . In StubHttpURLStreamHandler , we
override one method, openConnection , to open a connection to the given URL D .
You could also use anonymous inner classes for conciseness, but that approach
would make the code more difficult to read. Note that you haven't written the
StubHttpURLConnection class yet, which is the topic of the next section.
B
C
D
Search WWH ::




Custom Search