Java Reference
In-Depth Information
In the case of the MockInputStream class, the expectation for close is simple: we
always want it to be called once. But most of the time, the expectation for closeCount
depends on the code under test. A mock usually has a method like setExpected-
CloseCalls so that the test can tell the mock what to expect.
Let's modify the TestWebClient.testGetContentOk test method to use the new
MockInputStream :
[...]
public class TestWebClient {
@Test
public void testGetContentOk() throws Exception {
MockConnectionFactory mockConnectionFactory =
new MockConnectionFactory();
MockInputStream mockStream = new MockInputStream();
mockStream.setBuffer("It works");
mockConnectionFactory.setData(mockStream);
WebClient client = new WebClient();
String result = client.getContent(mockConnectionFactory);
assertEquals("It works", result);
mockStream.verify();
}
}
Instead of using a real ByteArrayInputStream as in previous tests, we now use the
MockInputStream . Note that we call the verify method of MockInputStream at the end
of the test to ensure that all expectations are met. The result of running the test is
shown in figure 7.4.
The test fails with the message close() should have been called once and
once only .
Why? Because we haven't closed the input stream in the WebClient.getContent
method. The same error would be raised if we were closing it twice or more, because
the test verifies that it's called once and only once.
Let's correct the code under test (see listing 7.14).
Figure 7.4
Running TestWebClient with the new close expectation
 
 
 
Search WWH ::




Custom Search