java需要h2数据库才能抛出jdbc异常

时间:2017-06-21 20:03:44

标签: java unit-testing jdbc h2

我正在为一些与数据库交互的代码编写测试。我的代码有一个查找BatchUpdateException的try-catch。但是,在我的Test类中,我使用内存数据库(H2),当插入失败时,它不会抛出BatchUpdateException。它会抛出org.h2.jdbc.JdbcSQLException

我希望能够用测试用例覆盖Catch子句。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

你能不能让你的测试代码抓住org.h2.jdbc.JdbcSQLException,然后抛出一个新的java.sql.BatchUpdateException?这似乎对我有用......

package h2demo;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class H2DemoMain {

    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:test")) {
            try (Statement st = conn.createStatement()) {
                // set up test environment
                st.execute("CREATE TABLE table1 (id INT PRIMARY KEY)");
                st.execute("INSERT INTO table1 (id) VALUES (2)");
            }
            try {
                doBatchUpdate(conn);
            } catch (BatchUpdateException bue) {
                System.out.println("BatchUpdateException caught: " + bue.getMessage());
                System.out.println();
                System.out.println("Update counts returned by exception:");
                for (int i : bue.getUpdateCounts()) {
                    System.out.println(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

    }

    private static int[] doBatchUpdate(Connection conn) throws SQLException {
        int[] updateCounts = null;
        try (PreparedStatement ps = conn.prepareStatement("INSERT INTO table1 (id) VALUES (?)")) {
            ps.setInt(1, 1);
            ps.addBatch();
            ps.setInt(1, 2);
            ps.addBatch();
            ps.setInt(1, 3);
            ps.addBatch();
            updateCounts = ps.executeBatch();
        } catch (org.h2.jdbc.JdbcSQLException jse) {
            throw new BatchUpdateException(jse.getMessage(), updateCounts, jse);
        }
        return updateCounts;
    }

}

...生成以下控制台(System.out)输出:

BatchUpdateException caught: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.TABLE1(ID)"; SQL statement:
INSERT INTO table1 (id) VALUES (?) [23505-196]

Update counts returned by exception:
1
-3
1