Deep stubbing in Mockito

Next version of Mockito, my favorite mocking/stubbing framework, will provide deep stubbing. This kind of test code will become possible:

@Test
public void canStubOneLevelDeep() {
    OutputStream out = new ByteArrayOutputStream();
    
    SocketFactory socketFactory = mock(SocketFactory.class, RETURNS_DEEP_STUBS);
    when(socketFactory.createSocket().getOutputStream()).thenReturn(out);

    assertThat(socketFactory.createSocket().getOutputStream()).isSameAs(out);
}

Notice the two chained calls in a when clause. Isn’t it cool? I think that’s cool.

I can make tests clearer in case of poorly designed production code. And who doesn’t write poorly designed code sometimes? I do more often than not. So why not have at least clearer tests?

It would be even cooler if we could get rid of the ulgy (very ugly?) RETURNS_DEEP_STUBS artefact and let the when clause sort things out on its own.

Hey, have you noticed I use Fest Assert, the best assertion library?

2 thoughts on “Deep stubbing in Mockito”

  1. Although I didn’t care much for mocking frameworks; too long tests methods with shitloads of recordings, I have learned to appreciate mocking again after I started working with Mockito.

    But when I do something with IO, in a lot of cases I prefer mini integration tests (this example would be an exception).

Comments are closed.