JDBCBase { protected final void withStatement(Connection connection, String sql, StatementBlock statementBlock) throws Exception { PreparedStatement statement = connection.prepareStatement(sql); checkNotNull(statement); try { statementBlock.use(statement); } finally { closeSilently(statement); } } protected  JDBCBase(String url, String username, @Nullable String password); synchronized final void initialize(); synchronized final void teardown();  }
@Test public void shouldClosePreparedStatementIfExceptionIsThrownInStatementBlock() throws Exception { when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement); final JDBCBase.StatementBlock mockStatementBlock = mock(JDBCBase.StatementBlock.class); doThrow(IllegalArgumentException.class).when(mockStatementBlock).use(mockPreparedStatement); assertThatExceptionIsThrown(new Callable<Void>() { @Override public Void call() throws Exception { jdbcTestSubclass.withStatement(mockConnection, "SOME SQL", mockStatementBlock); return null; } }, IllegalArgumentException.class); verify(mockPreparedStatement).close(); }
@Test public void shouldClosePreparedStatementIfExceptionIsThrownInStatementWithReturnBlock() throws Exception { when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement); final JDBCBase.StatementWithReturnBlock<?> mockStatementWithReturnBlock = mock(JDBCBase.StatementWithReturnBlock.class); doThrow(IllegalArgumentException.class).when(mockStatementWithReturnBlock).use(mockPreparedStatement); assertThatExceptionIsThrown(new Callable<Void>() { @Override public Void call() throws Exception { jdbcTestSubclass.withStatement(mockConnection, "SOME SQL", mockStatementWithReturnBlock); return null; } }, IllegalArgumentException.class); verify(mockPreparedStatement).close(); }