O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required