使用JUNIT测试JDBC代码

时间:2015-12-27 20:37:38

标签: java unit-testing junit

我正在使用DBUnit和H2数据库来测试Java代码。

在制作中,我们使用MySQL。需要测试的代码是

public int getReplicationLag(String endTime) throws SQLException, ClassNotFoundException {
    Class.forName(driverClass);
    Properties connProps = new Properties();
    connProps.put("user", userName);
    connProps.put("password", password);
    String query = "select time_to_sec(timediff(ts, ?)) from Foo";
    int currentLag = 0;
    try(Connection con = DriverManager.getConnection(connectionString, connProps)) {
        try (PreparedStatement stmt = con.prepareStatement(query)) {
            stmt.setString(1, endTime);
            try(ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    currentLag = rs.getInt(1);
                }
            }
        }
    }
    return currentLag;
}

我写了我的测试用例,但是当我执行测试用例时,它说

java.lang.AssertionError: Exception thrown Function "TIME_TO_SEC" 
not found; SQL statement:
select time_to_sec(timediff(ts, ?)) from Foo [90022-190] 
[Ljava.lang.StackTraceElement;@3152cf21
        at org.junit.Assert.fail(Assert.java:88)
        at 

因此似乎H2数据库中不存在time_to_sec函数。 所以现在该怎么办?开始针对mysql实例进行测试?它不会打破一些单元测试原则吗?因为针对真实数据库的测试看起来像是集成测试。 (我可能错了)。

在这种情况下你会做什么?以与H2兼容的方式更改查询? ..但后来我重新发明轮子,因为mysql已经给了我这个功能。

另外,如果我带入了mysql,那么我的测试变得复杂,因为现在我必须加密/解密凭据。 (这对H2来说不是问题)。

0 个答案:

没有答案
相关问题