java - 检查异常对 Mockito SQLException throw 无效
问题描述
我基本上想要的是全面覆盖下面的代码片段
public Connection getDbConnection() {
Logger logger = LoggerFactory.getLogger("DatabaseConnection.class");
PropertyUtility propUtility = new PropertyUtility();
Properties prop = propUtility.getDbProperty();
Connection conn = null;
try
{
final String dbUrl = prop.getProperty("db.url");
final String dbUsername = prop.getProperty("db.user");
final String dbPassword = prop.getProperty("db.password");
conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
}
catch (SQLException ex)
{
logger.error("Cannot connect to database server");
logger.error(ex.getMessage());
}
return conn;
}
我想模拟一个 SQLException throw 到 getDbConnection 中,以便它也涵盖捕获场景,这就是我到目前为止所拥有的。
DatabaseUtility db = new DatabaseUtility();
DatabaseUtility dbMock;
void setUp() throws Exception {
dbMock = mock(DatabaseUtility.class);
}
@Test
final void testGetDbPropertyFail () {
when(dbMock.getDbConnection()).thenThrow(new SQLException("TEST"));
assertEquals(null,db.getDbConnection());
}
当我尝试通过junit进行代码覆盖时,仍然没有覆盖catch场景,结果是“检查的异常对此方法无效”
我已经尝试过来自 stackoverflow 的其他可能的论坛,但没有一个对我有用。
解决方案
我猜这getDbConnection()
是一个方法DatabaseUtility
,你想对DatabaseUtility
类进行单元测试,对吧?
“Checked exception is invalid for this method”是字面意思,这意味着 Mockito 只允许模拟 throw Runtime exceptions
。
此外,您可以使用verify()
Mockito 提供的方法来验证模拟对象的状态变化或调用时间。(并且,对不起,mock
这意味着虚拟化目标测试模块的其他相关模块,但不要模拟目标,这样它将通过代码中的真实逻辑,而不是单元测试库提供的假接口。)
推荐阅读
- amazon-web-services - 如何在 Ubuntu 中使用 PuTTYgen 将 PEM 文件转换为 PPK?
- sql - 使用 SqlCommand 从子表更新父表
- android - 在没有模拟器的情况下调试反向 Android 应用程序以进行动态分析
- python - Ubuntu EC2 - 重启时运行 Python 脚本
- javascript - 调试这个并帮助找到解决这个问题
- python - 如何读取这个特定的 pbf 文件
- c++ - 在一定长度后从数组打印出时缺少整数
- tensorflow - 如何在 tensorboard 中可视化 K 折交叉验证
- javascript - 在 React 钩子中调用函数是可能的
- javascript - 从 e.target.parentNode 获取特定 div 后,我们如何访问它的某些属性/属性