Specification – error handling

What happens if a move could not be saved? Our helper method saveMove returns true or false depending on the MongoDB operation outcome. We might want to throw an exception when it returns false.

First things first: we should change the implementation of the before method and make sure that, by default, saveMove returns true:

@Before
public final void before() throws UnknownHostException {
  collection = mock(TicTacToeCollection.class);
  doReturn(true).when(collection).saveMove(any(TicTacToeBean.class));
  ticTacToe = new TicTacToe(collection);
}

Now that we have stubbed the mocked collection with what we think is the default behavior (return true when saveMove is invoked), we can proceed and write the specification:

@Test
public void whenPlayAndSaveReturnsFalseThenThrowException() {
  doReturn(false).when(collection).saveMove(any(TicTacToeBean.class));
  TicTacToeBean move = new TicTacToeBean(1, 1, 3, 'X');
  exception.expect(RuntimeException.class);
  ticTacToe.play(move.getX(), move.getY());
}

We're using Mockito to return false when saveMove is invoked. Since, in this case, we don't care about a specific invocation of saveMove, we used any(TicTacToeBean.class) as the method argument. This is another one of Mockito's static methods.

Once everything is set, we use a JUnit expectation in the same way as we did before throughout Chapter 3, Red-Green-Refactor – From Failure Through Success until Perfection.

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

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