Specification – error handling

Now let us contemplate the option that something might go wrong when using MongoDB. When, for example, an exception is thrown, we might want to return false from our saveMove method:

@Test
public void givenExceptionWhenSaveMoveThenReturnFalse() {
  doThrow(new MongoException("Bla"))    .when(mongoCollection).save(any(TicTacToeBean.class));
  doReturn(mongoCollection).when(collection).getMongoCollection();
  assertFalse(collection.saveMove(bean));
} 

Here, we introduce to another Mockito method: doThrow. It acts in a similar way to doReturn and throws an Exception when set conditions are fulfilled. The specification will throw the MongoException when the save method inside the mongoCollection class is invoked. This allows ...

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.