Bullet-proof JDBC tests by always calling the SQL DDL to dropo a table
even when a test fails.
@@ -18,7 +18,9 @@ package org.apache.logging.log4j.junit;
import java.sql.Connection;
import java.sql.Statement;
+import java.util.Objects;
+import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.appender.db.jdbc.ConnectionSource;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
@@ -40,15 +42,15 @@ public class JdbcRule implements TestRule {
/**
* Creates a JdbcRule using a {@link ConnectionSource} and a table creation statement.
*
- * @param connectionSource a source for obtaining a Connection
- * @param createTableStatement a SQL DDL statement to set up a table for use in a JUnit test
- * @param dropTableStatement a SQL DDL statement to drop the created table
+ * @param connectionSource a required source for obtaining a Connection.
+ * @param createTableStatement an optional SQL DDL statement to create a table for use in a JUnit test.
+ * @param dropTableStatement an optional SQL DDL statement to drop the created table.
*/
public JdbcRule(final ConnectionSource connectionSource, final String createTableStatement,
final String dropTableStatement) {
- this.dropTableStatement = dropTableStatement;
- this.connectionSource = connectionSource;
+ this.connectionSource = Objects.requireNonNull(connectionSource, "connectionSource");
this.createTableStatement = createTableStatement;
+ this.dropTableStatement = dropTableStatement;
}
public ConnectionSource getConnectionSource() {
@@ -61,13 +63,17 @@ public class JdbcRule implements TestRule {
return new org.junit.runners.model.Statement() {
@Override
public void evaluate() throws Throwable {
- try (final Connection connection = connectionSource.getConnection()) {
- try (final Statement statement = connection.createStatement()) {
+ try (final Connection connection = connectionSource.getConnection();
+ final Statement statement = connection.createStatement()) {
+ try {
+ if (StringUtils.isNotEmpty(createTableStatement)) {
statement.executeUpdate(createTableStatement);
}
base.evaluate();
- try (final Statement statement = connection.createStatement()) {
+ } finally {
+ if (StringUtils.isNotEmpty(dropTableStatement)) {
statement.executeUpdate(dropTableStatement);
+ }
statement.execute("SHUTDOWN");
}
}
