我想测试Class.forName(REDSHIFT_JDBC_DRIVER)部分并检查异常部分。有什么办法吗?
public Connection getConnection() throws SQLException {
Connection conn = null;
try {
Class.forName(REDSHIFT_JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, redShfitProperties);
} catch (ClassNotFoundException e) {
throw new RuntimeException("error", e);
} catch (SQLException e) {
log.error("Exception in getting connection", e);
throw e;
}
return conn;
}
答案 0 :(得分:1)
您可以在您的班级中插入班级名称,然后使用不存在的班级名称进行测试。
public class YourClass {
private final String jdbcDriver;
public YourClass() {
this(REDSHIFT_JDBC_DRIVER);
}
YourClass(String jdbcDriver) {
this.jdbcDriver = jdbcDriver;
}
public Connection getConnection() throws SQLException {
...
Class.forName(jdbcDriver);
...
}
}
您的测试可能如下所示:
@Test
public void fails_with_RuntimeException_when_driver_is_not_available() {
YourClass instance = new YourClass("this.class.does.not.exist");
assertThatThrownBy(() -> instance.getConnection(...))
isInstanceOf(RuntimeException.class);
}