【问题标题】:How to test Class.forName() using testng/junit?如何使用 testng/junit 测试 Class.forName()?
【发布时间】:2019-01-22 01:17:49
【问题描述】:

我想测试部分 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;
}

【问题讨论】:

  • 你想测试什么?您是否尝试测试类是否已加载(或)您是否尝试测试类加载失败时是否存在异常。
  • 正如我在问题中提到的,我正在寻找检查异常部分。

标签: unit-testing junit testng


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2012-10-24
    相关资源
    最近更新 更多