This last set of changes left me well positioned to implement the various aspects of the output. Commit [99cb54b] introduced an effective but somewhat awkward test to verify that System.out
was used for normal output. I call it awkward because of the use of the copiedToOutput
variable that needed checking in the override of retrieve()
, shown in Listing 14-7. This amounted to a hand-rolled mock. If I left out the flag, I would have no guarantee that copyToOutput()
was called and therefore that its assertion had been evaluated.
public void testRetrieve_StandardOutput()
throws IOException, URISyntaxException {
final String expectedContent = "This should go to stdout";
Target sut = new Target(EXAMPLE_URI, false) {
boolean copiedToOutput = false;
@Override
public void retrieve()
throws IOException, URISyntaxException {
super.retrieve();
assertThat(copiedToOutput, is(true));
}
@Override
protected void retrieveResponse()
throws IOException, URISyntaxException {
setResponse(
WebRetrieverTest.createMockResponse(expectedContent));
}
@Override
protected void copyToOutput(
InputStream content, OutputStream output)
throws IOException {
assertThat(System.out, is(output));
copiedToOutput = true;
}
};
sut.retrieve();
}
The following commit, [f89bf38], refactors the anonymous inner class to an explicit nested class and turns it into a spy rather than a mock. This yields a nicer-looking test as well as a reusable spy for the other output variations (Listing 14-8).
public void testRetrieve_StandardOutput()
throws IOException, URISyntaxException {
OutputSpyTarget sut =
new OutputSpyTarget(EXAMPLE_URI, false);
sut.retrieve();
OutputStream outputStream = sut.getOutputStream();
assertThat(outputStream, is(notNullValue()));
assertThat(System.out, is(outputStream));
}
class OutputSpyTarget extends Target {
OutputStream outputStream = null;
public OutputSpyTarget(String URI, boolean writeToFile)
throws URISyntaxException {
super(URI, writeToFile);
}
@Override
protected void retrieveResponse()
throws IOException, URISyntaxException {
setResponse(WebRetrieverTest.createMockResponse(""));
}
@Override
protected void copyToOutput(
InputStream content, OutputStream output)
throws IOException {
outputStream = output;
}
public OutputStream getOutputStream() {
return outputStream;
}
}
The remainder of the commits use the OutputSpyTarget
to verify that it writes to a file and that it fails when no file path is given.
18.226.187.233