I'm trying to write a unit test for some code that opens a database connection and performs some operations on the database. I want to assert that the connection is correctly closed, even if an Exception is thrown.
The code I want to test looks like this:
public void methodToTest(final String aName) {
final String sqlDeleteStatement = "DELETE FROM " + DB_FULL_TABLE + " WHERE name=?";
try (final Connection connection = this.dataSource.getConnection();
final PreparedStatement deleteStatement = connection.prepareStatement(sqlDeleteStatement);) {
connection.setAutoCommit(true);
deleteStatement.setString(1, aName);
deleteStatement.executeUpdate();
}
catch (final SQLException e) {
// handle error
}
}
I'm currently using jMock to create mock instances for the datasource and connection objects and simulate that an Exception is thrown in connection.prepareStatement
:
public void testConnectionClosed() throws Exception {
final Mockery mockery = new Mockery();
final DataSource dataSource = mockery.mock(DataSource.class);
final Connection connection = mockery.mock(Connection.class);
final String exceptionMessage = "intentionally thrown " + UUID.randomUUID();
mockery.checking(new Expectations() {{
oneOf(dataSource).getConnection();
will(returnValue(connection));
oneOf(connection).prepareStatement(with(any(String.class)));
will(throwException(new SQLException(exceptionMessage)));
oneOf(connection).close();
}});
final ClassUnderTest cut = new ClassUnderTest(dataSource);
cut.methodToTest("someName");
mockery.assertIsSatisfied();
}
The problem I'm facing is, that the test is green with and without the expectation on connection.close()
. Without the expectation I see a suppressed org.jmock.api.ExcpectationError
:
Suppressed: unexpected invocation: java.sql.Connection1370903230.close()
But the test is not failing as the error is raised inside the implicit finally block of the try-with-resource statement.
I don't want to rewrite the code just to make this test meaningful, but I want to ensure proper resource handling as well without requiring too much knowledge about very specific implementation details like the usage of try-with-resource.
Is there a way to achieve this with jMock?
And no, I'm not asking for a recommendation on a library. So please don't mark as off topic.