dimanche 27 décembre 2015

Testing JDBC Code with JUNIT

I am using DBUnit and H2 database to test Java code.

In production, we use MySQL. The code which needs to be tested is

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;
}

I wrote my test case but when I execute the test case it says

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 

So it seems that the time_to_sec function doesn't exist in the H2 Database. So now what should I do? start testing against a mysql instance? won't it break some unit testing principles? because testing against a real DB seems like an integration test. (i may be wrong).

What would you do in such case? change the query in a way that is compatible with H2? .. but then I am reinventing the wheel because mysql already gives me that functionality.

Also, if I do bring in mysql then my tests become complex because now I have to encrypt/decrypt credentials. (something which was not a problem with H2).

Aucun commentaire:

Enregistrer un commentaire