My understanding is, that Mockito.spy(object)
wraps a proxy around an existing object. This proxy delegates the method calls to the spied object and allows further verification (So it's different to a mock which provides no implementation).
I want to spy on an input stream to ensure the close/read methods are properly called. But the following (simple) spy code doesn't work:
// Create a spy input stream object
String testData = "Hello";
InputStream inputStream = new ByteArrayInputStream(testData.getBytes(StandardCharsets.UTF_8));
InputStream spiedInputStream = spy(inputStream);
assertEquals(testData.getBytes(StandardCharsets.UTF_8).length, spiedInputStream.available()); // Fails: Expected 5, Actual 0
// Read the input stream
byte [] readData = new byte[testData.length()];
assertEquals(testData.getBytes(StandardCharsets.UTF_8).length, spiedInputStream.read(readData)); // Fails: Expected 5, Actual -1
assertEquals(testData, new String(readData, StandardCharsets.UTF_8)); // Fails, readData is fully zeroed
So what am I doing wrong (Ubuntu 22.04, Java 17, Mockito 4.7.0)