首页 > 解决方案 > 检查异常对 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 的其他可能的论坛,但没有一个对我有用。

标签: javajunitmockito

解决方案


我猜这getDbConnection()是一个方法DatabaseUtility,你想对DatabaseUtility类进行单元测试,对吧?

“Checked exception is invalid for this method”是字面意思,这意味着 Mockito 只允许模拟 throw Runtime exceptions

此外,您可以使用verify()Mockito 提供的方法来验证模拟对象的状态变化或调用时间。(并且,对不起,mock这意味着虚拟化目标测试模块的其他相关模块,但不要模拟目标,这样它将通过代码中的真实逻辑,而不是单元测试库提供的假接口。)

什么是嘲笑?

https://www.baeldung.com/mockito-verify


推荐阅读