DataSourceHealthChecker { public Result check(DataSource dataSource) { try (Connection connection = dataSource.getConnection()) { if (connection == null) { return Result.unhealthy("No database connection could be established"); } if (!connection.isValid(1)) { return Result.unhealthy("Connection is not valid"); } } catch (SQLException e) { return Result.unhealthy(e); } return Result.healthy(); }  Result check(DataSource dataSource);  }
@Test public void checkHealthy() throws Exception { Connection connectionMock = Mockito.mock(Connection.class); when(connectionMock.isValid(anyInt())).thenReturn(true); when(dataSource.getConnection()).thenReturn(connectionMock); assertThat(healthChecker.check(dataSource).isHealthy(), is(true)); }
@Test public void checkUnhealthyCloseConnection() throws Exception { Connection connectionMock = Mockito.mock(Connection.class); doThrow(new SQLException()).when(connectionMock).close(); when(connectionMock.isValid(anyInt())).thenReturn(true); when(dataSource.getConnection()).thenReturn(connectionMock); assertThat(healthChecker.check(dataSource).isHealthy(), is(false)); }
@Test public void checkUnhealthyNoConnection() { assertThat(healthChecker.check(dataSource).isHealthy(), is(false)); }
@Test public void checkUnhealthyConnectionInvalid() throws Exception { Connection connectionMock = Mockito.mock(Connection.class); when(connectionMock.isValid(anyInt())).thenReturn(false); when(dataSource.getConnection()).thenReturn(connectionMock); assertThat(healthChecker.check(dataSource).isHealthy(), is(false)); }
@Test public void checkUnhealthySqlException() throws Exception { doThrow(new SQLException()).when(dataSource).getConnection(); assertThat(healthChecker.check(dataSource).isHealthy(), is(false)); }
@Test public void checkUnhealthyExceptionOnIsValid() throws Exception { Connection connectionMock = Mockito.mock(Connection.class); doThrow(new SQLException()).when(connectionMock).isValid(anyInt()); when(dataSource.getConnection()).thenReturn(connectionMock); assertThat(healthChecker.check(dataSource).isHealthy(), is(false)); }