【问题标题】:java need h2 database to throw jdbc exceptionjava需要h2数据库抛出jdbc异常
【发布时间】:2017-06-21 20:03:44
【问题描述】:
我正在为一些与数据库交互的代码编写测试。我的代码有一个寻找BatchUpdateException 的try-catch。但是,在我的测试类中,我使用的是内存数据库 (H2),当插入失败时,它不会抛出 BatchUpdateException。它会抛出一个org.h2.jdbc.JdbcSQLException。
我希望能够用测试用例覆盖 Catch 子句。我该怎么做呢?
【问题讨论】:
标签:
java
unit-testing
jdbc
h2
【解决方案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