Java Reference
In-Depth Information
return
connection.getInputStream();
}
}
Now we can easily test the
getContent
method by writing a mock for
Connection-
Factory
(see listing 7.11).
Listing 7.11
MockConnectionFactory.java
[...]
import
java.io.InputStream;
public class
MockConnectionFactory
implements
ConnectionFactory {
private
InputStream inputStream;
public void
setData(InputStream stream) {
this
.inputStream = stream;
}
public
InputStream getData()
throws
Exception {
return this
.inputStream;
}
}
As usual, the mock doesn't contain any logic and is completely controllable from the
outside (by calling the
setData
method). We can now easily rewrite the test to use
MockConnectionFactory
, as demonstrated in listing 7.12.
Listing 7.12
Refactored
WebClient
test using
MockConnectionFactory
[...]
import
java.io.ByteArrayInputStream;
public class
TestWebClient {
@Test
public void
testGetContentOk()
throws
Exception {
MockConnectionFactory mockConnectionFactory =
new
MockConnectionFactory();
mockConnectionFactory.setData(
new
ByteArrayInputStream("It works".getBytes()));
WebClient client =
new
WebClient();
String result = client.getContent(mockConnectionFactory);
assertEquals("It works", result);
}
}
We've achieved our initial goal: to unit test the code logic of the
WebClient.get-
Content
method. In the process we had to refactor it for the test, which led to a more
extensible implementation that's better able to cope with change.
7.5
Using mocks as Trojan horses
Mock objects are Trojan horses, but they're not malicious. Mocks replace real objects
from the inside, without the calling classes being aware of it. Mocks have access to