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 values. This is confirmed in the second line, where we assert that the drop method returns false. Further on, we specify that our mocked object collection should return true when the drop method is invoked. Finally, we assert that the drop method returns true.

We created a mock object that returns default values and, for one of its methods, defined what should be the return value. At no point was a real object used.

Later on, we'll work with spies that have this logic inverted; an object uses real methods unless specified otherwise. We'll see and learn more about mocking soon when we start extending our Tic-Tac-Toe application. Right now, we'll take a look at one of the Java mocking frameworks called Mockito.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.219