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 us to assert that our saveMove method returns false when an exception is thrown.