Deep stubbing in Mockito
January 19th, 2010
1 comment
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?