【发布时间】:2017-07-19 08:36:18
【问题描述】:
我正在尝试为一些打开数据库连接并对数据库执行一些操作的代码编写单元测试。我想断言连接已正确关闭,即使抛出异常也是如此。
我要测试的代码是这样的:
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
}
}
我目前正在使用 jMock 为数据源和连接对象创建模拟实例,并模拟在 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();
}
我面临的问题是,测试是绿色的,并且没有对connection.close() 的期望。不出所料,我看到了一个被压制的org.jmock.api.ExcpectationError:
Suppressed: unexpected invocation: java.sql.Connection1370903230.close()
但是测试并没有失败,因为在 try-with-resource 语句的隐式 finally 块中引发了错误。
我不想仅仅为了让这个测试有意义而重写代码,但我想确保正确的资源处理,而不需要太多关于非常具体的实现细节的知识,比如 try-with-resource 的使用。
有没有办法用 jMock 实现这一点?
不,我不是在寻求关于图书馆的推荐。所以请不要标记为离题。
【问题讨论】:
标签: java unit-testing mocking jmock