MongoStatusDetailIndicator implements StatusDetailIndicator { @Override public List<StatusDetail> statusDetails() { String databaseStatusName = "MongoDB Status"; Document document = new Document().append("ping", 1); Document answer; try { answer = mongoDatabase.runCommand(document); } catch (MongoTimeoutException e) { return singletonList( statusDetail(databaseStatusName, ERROR, "Mongo database check ran into timeout (" + e.getMessage() + ").") ); } catch (Exception other) { return singletonList( statusDetail(databaseStatusName, ERROR, "Exception during database check (" + other.getMessage() + ").") ); } if (answer != null && answer.get("ok") != null && (Double)answer.get("ok") == 1.0d) { return singletonList( statusDetail(databaseStatusName, OK, "Mongo database is reachable.") ); } return singletonList( statusDetail(databaseStatusName, ERROR, "Mongo database unreachable or ping command failed.") ); } @Autowired  MongoStatusDetailIndicator(MongoDatabase mongoDatabase); @Override List<StatusDetail> statusDetails();  }
@Test public void shouldReturnOKStatus() { when(mongoDatabase.runCommand(new Document().append("ping", 1))).thenReturn(new Document().append("ok", 1.0d)); final StatusDetail statusDetail = testee.statusDetails().get(0); assertThat(statusDetail.getStatus(), is(OK)); }
@Test public void shouldReturnErrorStatusWhenDatabaseDoesntReturnOKForPing() { when(mongoDatabase.runCommand(new Document().append("ping", 1))).thenReturn(new Document().append("error", 1.0d)); final StatusDetail statusDetail = testee.statusDetails().get(0); assertThat(statusDetail.getStatus(), is(ERROR)); assertThat(statusDetail.getMessage(), containsString("Mongo database unreachable or ping command failed.")); }
@Test public void shouldReturnErrorStatusWhenDatabaseTimesOut() { when(mongoDatabase.runCommand(new Document().append("ping", 1))).thenThrow(new MongoTimeoutException("Timeout")); final StatusDetail statusDetail = testee.statusDetails().get(0); assertThat(statusDetail.getStatus(), is(ERROR)); assertThat(statusDetail.getMessage(), containsString("Mongo database check ran into timeout")); }
@Test public void shouldReturnErrorStatusOnAnyException() { when(mongoDatabase.runCommand(new Document().append("ping", 1))).thenThrow(new MongoException("SomeException")); final StatusDetail statusDetail = testee.statusDetails().get(0); assertThat(statusDetail.getStatus(), is(ERROR)); assertThat(statusDetail.getMessage(), containsString("Exception during database check")); }