Steve
Steve

Reputation: 4691

java need h2 database to throw jdbc exception

I am writing tests for some code that interacts with a database. My code has a try-catch that looks for a BatchUpdateException. However, in my Test class I'm using an in-memory database (H2), and when that fails an insert it does not throw a BatchUpdateException. It throws a org.h2.jdbc.JdbcSQLException.

I'd like to be able to cover with Catch clause with a test case. How can I go about doing that?

Upvotes: 1

Views: 1770

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123609

Can you not just have your test code catch the org.h2.jdbc.JdbcSQLException and then throw a new java.sql.BatchUpdateException? This seems to work for me ...

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

}

... producing the following console (System.out) output:

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

Upvotes: 1

Related Questions