Mock objects

Mock objects simulate the behavior of real (often complex) objects. They allow us to create an object that will replace the real one used in the implementation code. A mocked object will expect a defined method with defined arguments to return the expected result. It knows in advance what is supposed to happen and how we expect it to react.

Let's take a look at one simple example:

TicTacToeCollection collection = mock(TicTacToeCollection.class); 
assertThat(collection.drop()).isFalse();doReturn(true).when(collection).drop(); 

assertThat(collection.drop()).isTrue();

First, we defined collection to be a mock of TicTacToeCollection. At this moment, all methods from this mocked object are fake and, in the case of Mockito, return default ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.