Mockito SQLException 抛出的检查异常无效

Check exception invalid for 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 抛出到 getDbConnection 中,以使其也涵盖 catch 场景,这就是我目前所拥有的。

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 场景仍未被覆盖,结果显示“已检查的异常对于此方法无效”

我尝试了 Whosebug 中其他可能的论坛,none 对我有用。

我猜 getDbConnection()DatabaseUtility 的一个方法,你想对 DatabaseUtility class 进行单元测试,对吗?

“Checked exception 对于此方法无效”是字面意思,这意味着 Mockito 只允许 mock 抛出 Runtime exceptions.

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

What is Mocking?

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