Search code examples
javaunit-testingmockitostubbing

Why is Mockito behaving weird with InputStreams?


While debugging I came across something incredibly strange using Mockito 1.10. I was hoping someone could explain the behavior perceived here:

When I run the following, my thread hangs and my test never returns. CPU of the Java process created goes astronomical too!

@Test(expected = IOException.class)
public void mockitoWeirdness() throws IOException {
    final InputStream mis = mock(InputStream.class);
    doThrow(IOException.class).when(mis).read();
    ByteStreams.copy(mis, new ByteArrayOutputStream());
}

When I manually stub this method as follows, the expected IOException is thrown:

@Test(expected = IOException.class)
public void nonMockitoExpected() throws IOException {
    final InputStream mis = new InputStream() {

        @Override
        public int read() throws IOException {
            throw new IOException();
        }
    };
    ByteStreams.copy(mis, new ByteArrayOutputStream());
}

Any help understanding how and why the mockito method is failing would be fantastic.


Solution

  • If you take a look at the ByteStreams implementation, you can see that the read(buf) method is used. In your case it returns null because there is no mock definition for it and this causes an endless loop in the copy method.

    You may either change the default mock behaviour or manually add a definition for the read(buff) method.