From ff40d72923a6b480ee0d4795ba8ed417d079baf1 Mon Sep 17 00:00:00 2001 From: David Gageot Date: Thu, 12 Jul 2012 08:17:24 +0200 Subject: [PATCH] Improve test code --- .../DefaultResourcePermissionsTest.java | 6 +- .../core/persistence/AbstractDaoTestCase.java | 161 +++++++++--------- .../core/persistence/DatabaseCommands.java | 19 +-- .../sonar/core/persistence/H2Database.java | 28 ++- .../core/persistence/H2DatabaseTest.java | 15 +- .../sonar/core/persistence/MyBatisTest.java | 22 +-- .../core/resource/ResourceIndexerDaoTest.java | 16 +- .../jpa/test/AbstractDbUnitTestCase.java | 106 +++++------- 8 files changed, 180 insertions(+), 193 deletions(-) diff --git a/plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/security/DefaultResourcePermissionsTest.java b/plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/security/DefaultResourcePermissionsTest.java index 319c9b1d27e..9d098414fbb 100644 --- a/plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/security/DefaultResourcePermissionsTest.java +++ b/plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/security/DefaultResourcePermissionsTest.java @@ -42,7 +42,7 @@ public class DefaultResourcePermissionsTest extends AbstractDaoTestCase { // do not insert duplicated rows permissions.grantGroupRole(project, "sonar-administrators", "admin"); - checkColumns("grantGroupRole", "group_roles", "group_id", "resource_id", "role"); + checkTables("grantGroupRole", new String[] {"id"}, "group_roles"); } @Test @@ -86,7 +86,7 @@ public class DefaultResourcePermissionsTest extends AbstractDaoTestCase { // do not insert duplicated rows permissions.grantUserRole(project, "marius", "admin"); - checkColumns("grantUserRole", "user_roles", "user_id", "resource_id", "role"); + checkTables("grantUserRole", new String[] {"id"}, "user_roles"); } @Test @@ -151,4 +151,4 @@ public class DefaultResourcePermissionsTest extends AbstractDaoTestCase { // does not exist assertThat(permissions.hasRoles(new Project("not_found"))).isFalse(); } -} \ No newline at end of file +} diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/AbstractDaoTestCase.java b/sonar-core/src/test/java/org/sonar/core/persistence/AbstractDaoTestCase.java index b7646afb3cd..0c64f2ef419 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/AbstractDaoTestCase.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/AbstractDaoTestCase.java @@ -21,67 +21,61 @@ package org.sonar.core.persistence; import com.google.common.collect.Maps; import com.google.common.io.Closeables; +import org.apache.commons.io.IOUtils; import org.dbunit.Assertion; import org.dbunit.DataSourceDatabaseTester; import org.dbunit.DatabaseUnitException; import org.dbunit.IDatabaseTester; import org.dbunit.database.DatabaseConfig; import org.dbunit.database.IDatabaseConnection; +import org.dbunit.dataset.CompositeDataSet; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.ReplacementDataSet; import org.dbunit.dataset.filter.DefaultColumnFilter; import org.dbunit.dataset.xml.FlatXmlDataSet; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; import org.sonar.api.config.Settings; import org.sonar.core.config.Logback; import java.io.InputStream; +import java.sql.Connection; import java.sql.SQLException; import static org.junit.Assert.fail; public abstract class AbstractDaoTestCase { private static Database database; - private static MyBatis myBatis; private static DatabaseCommands databaseCommands; - - private IDatabaseTester databaseTester; - private IDatabaseConnection connection; + private static IDatabaseTester databaseTester; + private static MyBatis myBatis; @BeforeClass - public static void startDatabase() throws Exception { + public static void startDatabase() { Settings settings = new Settings().setProperties(Maps.fromProperties(System.getProperties())); boolean hasDialect = settings.hasKey("sonar.jdbc.dialect"); if (hasDialect) { database = new DefaultDatabase(settings); } else { - database = new H2Database(); + database = new H2Database("sonarMyBatis"); } database.start(); + databaseCommands = DatabaseCommands.forDialect(database.getDialect()); + databaseTester = new DataSourceDatabaseTester(database.getDataSource()); + myBatis = new MyBatis(database, settings, new Logback()); myBatis.start(); - - databaseCommands = DatabaseCommands.forDialect(database.getDialect()); } @Before public void setupDbUnit() throws SQLException { - databaseCommands.truncateDatabase(myBatis.openSession().getConnection()); - databaseTester = new DataSourceDatabaseTester(database.getDataSource()); - } - - @After - public void stopConnection() throws Exception { - if (databaseTester != null) { - databaseTester.onTearDown(); - } - if (connection != null) { - connection.close(); - } + databaseCommands.truncateDatabase(database.getDataSource().getConnection()); } @AfterClass @@ -95,90 +89,113 @@ public abstract class AbstractDaoTestCase { return myBatis; } - protected void setupData(String testName) { - InputStream stream = null; + protected void setupData(String... testNames) { + InputStream[] streams = new InputStream[testNames.length]; try { - String className = getClass().getName(); - className = String.format("/%s/%s.xml", className.replace(".", "/"), testName); - stream = getClass().getResourceAsStream(className); - if (stream == null) { - throw new RuntimeException("Test not found :" + className); + for (int i = 0; i < testNames.length; i++) { + String className = getClass().getName(); + className = String.format("/%s/%s.xml", className.replace(".", "/"), testNames[i]); + streams[i] = getClass().getResourceAsStream(className); + if (streams[i] == null) { + throw new RuntimeException("Test not found :" + className); + } } - setupData(stream); + setupData(streams); + } finally { - Closeables.closeQuietly(stream); + for (InputStream stream : streams) { + IOUtils.closeQuietly(stream); + } } } - private void setupData(InputStream dataStream) { + private void setupData(InputStream... dataSetStream) { + IDatabaseConnection connection = null; try { - ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(dataStream)); - dataSet.addReplacementObject("[null]", null); - dataSet.addReplacementObject("[false]", databaseCommands.getFalse()); - dataSet.addReplacementObject("[true]", databaseCommands.getTrue()); + IDataSet[] dataSets = new IDataSet[dataSetStream.length]; + for (int i = 0; i < dataSetStream.length; i++) { + dataSets[i] = getData(dataSetStream[i]); + } + databaseTester.setDataSet(new CompositeDataSet(dataSets)); - databaseTester.setDataSet(dataSet); - connection = databaseTester.getConnection(); + connection = createConnection(); - connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory()); databaseCommands.getDbunitDatabaseOperation().execute(connection, databaseTester.getDataSet()); - } catch (Exception e) { throw translateException("Could not setup DBUnit data", e); + } finally { + closeQuietly(connection); + } + } + + private void closeQuietly(IDatabaseConnection connection) { + try { + if (connection != null) { + connection.close(); + } + } catch (SQLException e) { } } protected void checkTables(String testName, String... tables) { - checkTables(testName, new String[]{}, tables); + checkTables(testName, new String[0], tables); } protected void checkTables(String testName, String[] excludedColumnNames, String... tables) { + IDatabaseConnection connection = null; try { - IDataSet dataSet = getCurrentDataSet(); + connection = createConnection(); + + IDataSet dataSet = connection.createDataSet(); IDataSet expectedDataSet = getExpectedData(testName); for (String table : tables) { ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table), excludedColumnNames); - Assertion.assertEquals(expectedDataSet.getTable(table), filteredTable); + ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames); + Assertion.assertEquals(filteredExpectedTable, filteredTable); } - } catch (DataSetException e) { - throw translateException("Error while checking results", e); } catch (DatabaseUnitException e) { fail(e.getMessage()); + } catch (SQLException e) { + throw translateException("Error while checking results", e); + } finally { + closeQuietly(connection); } } - /** - * Opposite of {@link #checkTables(String, String[], String...)}. - */ - protected void checkColumns(String testName, String table, String... columns) { + protected void assertEmptyTables(String... emptyTables) { + IDatabaseConnection connection = null; try { - IDataSet dataSet = getCurrentDataSet(); - IDataSet expectedDataSet = getExpectedData(testName); - ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns); - ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns); - Assertion.assertEquals(filteredExpectedTable, filteredTable); - - } catch (DataSetException e) { - throw translateException("Error while checking columns", e); - } catch (DatabaseUnitException e) { - fail(e.getMessage()); + connection = createConnection(); + + IDataSet dataSet = connection.createDataSet(); + for (String table : emptyTables) { + try { + Assert.assertEquals("Table " + table + " not empty.", 0, dataSet.getTable(table).getRowCount()); + } catch (DataSetException e) { + throw translateException("Error while checking results", e); + } + } + } catch (SQLException e) { + throw translateException("Error while checking results", e); + } finally { + closeQuietly(connection); } } - protected void assertEmptyTables(String... emptyTables) { - for (String table : emptyTables) { - try { - Assert.assertEquals("Table " + table + " not empty.", 0, getCurrentDataSet().getTable(table).getRowCount()); - } catch (DataSetException e) { - throw translateException("Error while checking results", e); - } + private IDatabaseConnection createConnection() { + try { + IDatabaseConnection connection = databaseTester.getConnection(); + connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory()); + return connection; + } catch (Exception e) { + throw translateException("Error while getting connection", e); } } private IDataSet getExpectedData(String testName) { String className = getClass().getName(); - className = String.format("/%s/%s-result.xml", className.replace(".", "/"), testName); + className = String.format("/%s/%s-result.xml", className.replace('.', '/'), testName); InputStream in = getClass().getResourceAsStream(className); try { @@ -200,21 +217,13 @@ public abstract class AbstractDaoTestCase { } } - private IDataSet getCurrentDataSet() { - try { - return connection.createDataSet(); - } catch (SQLException e) { - throw translateException("Could not create the current dataset", e); - } - } - private static RuntimeException translateException(String msg, Exception cause) { RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage())); runtimeException.setStackTrace(cause.getStackTrace()); return runtimeException; } - protected IDatabaseConnection getConnection() { - return connection; + protected Connection getConnection() throws SQLException { + return database.getDataSource().getConnection(); } } diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/DatabaseCommands.java b/sonar-core/src/test/java/org/sonar/core/persistence/DatabaseCommands.java index 0eb249ab34a..2c1b44fd0d5 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/DatabaseCommands.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/DatabaseCommands.java @@ -41,8 +41,7 @@ import java.util.Arrays; import java.util.List; public abstract class DatabaseCommands { - - private IDataTypeFactory dbUnitFactory; + private final IDataTypeFactory dbUnitFactory; private DatabaseCommands(IDataTypeFactory dbUnitFactory) { this.dbUnitFactory = dbUnitFactory; @@ -52,20 +51,20 @@ public abstract class DatabaseCommands { public abstract List resetPrimaryKey(String table); - Object getTrue() { + public Object getTrue() { return Boolean.TRUE; } - Object getFalse() { + public Object getFalse() { return Boolean.FALSE; } - IDataTypeFactory getDbUnitFactory() { + public IDataTypeFactory getDbUnitFactory() { return dbUnitFactory; } - DatabaseOperation getDbunitDatabaseOperation() { - return DatabaseOperation.CLEAN_INSERT; + public DatabaseOperation getDbunitDatabaseOperation() { + return new InsertIdentityOperation(DatabaseOperation.INSERT); } static final DatabaseCommands H2 = new DatabaseCommands(new H2DataTypeFactory()) { @@ -92,7 +91,7 @@ public abstract class DatabaseCommands { } @Override - DatabaseOperation getDbunitDatabaseOperation() { + public DatabaseOperation getDbunitDatabaseOperation() { return new InsertIdentityOperation(DatabaseOperation.CLEAN_INSERT); } }; @@ -125,12 +124,12 @@ public abstract class DatabaseCommands { } @Override - Object getTrue() { + public Object getTrue() { return 1; } @Override - Object getFalse() { + public Object getFalse() { return 0; } }; diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/H2Database.java b/sonar-core/src/test/java/org/sonar/core/persistence/H2Database.java index 3767121de0d..d93f3f0fd41 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/H2Database.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/H2Database.java @@ -37,28 +37,29 @@ import java.util.Properties; * @since 3.2 */ public class H2Database implements Database { - private static BasicDataSource datasource; + private final String name; + private BasicDataSource datasource; + + /** + * IMPORTANT: change DB name in order to not conflict with {@link DefaultDatabaseTest} + */ + public H2Database(String name) { + this.name = name; + } public H2Database start() { - if (datasource == null) { - startDatabase(); - createSchema(); - } + startDatabase(); + createSchema(); return this; } - /** - * IMPORTANT: DB name changed from "sonar" to "sonar2" in order to not conflict with {@link DefaultDatabaseTest} - */ private void startDatabase() { try { datasource = new BasicDataSource(); datasource.setDriverClassName("org.h2.Driver"); datasource.setUsername("sonar"); datasource.setPassword("sonar"); - datasource.setUrl("jdbc:h2:mem:sonar2"); - datasource.setMaxActive(2); - datasource.setMaxIdle(2); + datasource.setUrl("jdbc:h2:mem:" + name); } catch (Exception e) { throw new IllegalStateException("Fail to start H2", e); } @@ -84,10 +85,7 @@ public class H2Database implements Database { public H2Database stop() { try { - if (datasource != null) { - datasource.close(); - datasource = null; - } + datasource.close(); } catch (SQLException e) { // Ignore error } diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/H2DatabaseTest.java b/sonar-core/src/test/java/org/sonar/core/persistence/H2DatabaseTest.java index f896c62a9f8..1d6e450103f 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/H2DatabaseTest.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/H2DatabaseTest.java @@ -19,7 +19,8 @@ */ package org.sonar.core.persistence; -import org.apache.commons.dbcp.BasicDataSource; +import org.junit.After; + import org.junit.Before; import org.junit.Test; @@ -29,14 +30,14 @@ import java.sql.SQLException; import static org.fest.assertions.Assertions.assertThat; public class H2DatabaseTest { - H2Database db = new H2Database(); + H2Database db = new H2Database("sonar2"); @Before public void startDb() { db.start(); } - @Before + @After public void stopDb() { db.stop(); } @@ -49,12 +50,4 @@ public class H2DatabaseTest { assertThat(tableCount).isGreaterThan(30); } - - @Test - public void shouldLimitThePoolSize() { - BasicDataSource dataSource = (BasicDataSource) db.getDataSource(); - - assertThat(dataSource.getMaxActive()).isEqualTo(2); - assertThat(dataSource.getMaxIdle()).isEqualTo(2); - } } diff --git a/sonar-core/src/test/java/org/sonar/core/persistence/MyBatisTest.java b/sonar-core/src/test/java/org/sonar/core/persistence/MyBatisTest.java index fff30b032a7..576808ec63e 100644 --- a/sonar-core/src/test/java/org/sonar/core/persistence/MyBatisTest.java +++ b/sonar-core/src/test/java/org/sonar/core/persistence/MyBatisTest.java @@ -36,12 +36,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class MyBatisTest { - private static H2Database database; + private Logback logback = mock(Logback.class); @BeforeClass public static void start() { - database = new H2Database(); + database = new H2Database("sonar2"); database.start(); } @@ -52,7 +52,7 @@ public class MyBatisTest { @Test public void shouldConfigureMyBatis() { - MyBatis myBatis = new MyBatis(database, new Settings(), new Logback()); + MyBatis myBatis = new MyBatis(database, new Settings(), logback); myBatis.start(); Configuration conf = myBatis.getSessionFactory().getConfiguration(); @@ -63,7 +63,7 @@ public class MyBatisTest { @Test public void shouldOpenBatchSession() { - MyBatis myBatis = new MyBatis(database, new Settings(), new Logback()); + MyBatis myBatis = new MyBatis(database, new Settings(), logback); myBatis.start(); SqlSession session = myBatis.openBatchSession(); @@ -77,9 +77,9 @@ public class MyBatisTest { @Test public void log_sql_requests() { - Logback logback = mock(Logback.class); - Settings settings = new Settings(); - settings.setProperty("sonar.showSql", true); + Settings settings = new Settings() + .setProperty("sonar.showSql", true); + MyBatis myBatis = new MyBatis(database, settings, logback); myBatis.start(); @@ -88,10 +88,10 @@ public class MyBatisTest { @Test public void log_sql_requests_and_responses() { - Logback logback = mock(Logback.class); - Settings settings = new Settings(); - settings.setProperty("sonar.showSql", true); - settings.setProperty("sonar.showSqlResults", true); + Settings settings = new Settings() + .setProperty("sonar.showSql", true) + .setProperty("sonar.showSqlResults", true); + MyBatis myBatis = new MyBatis(database, settings, logback); myBatis.start(); diff --git a/sonar-core/src/test/java/org/sonar/core/resource/ResourceIndexerDaoTest.java b/sonar-core/src/test/java/org/sonar/core/resource/ResourceIndexerDaoTest.java index e483fdb7245..7e5cb62ba2d 100644 --- a/sonar-core/src/test/java/org/sonar/core/resource/ResourceIndexerDaoTest.java +++ b/sonar-core/src/test/java/org/sonar/core/resource/ResourceIndexerDaoTest.java @@ -47,7 +47,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexResource(10, "ZipUtils", "FIL", 8); - checkTables("shouldIndexResource", new String[]{"id"}, "resource_index"); + checkTables("shouldIndexResource", new String[] {"id"}, "resource_index"); } @Test @@ -56,7 +56,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexProjects(); - checkTables("shouldIndexProjects", new String[]{"id"}, "resource_index"); + checkTables("shouldIndexProjects", new String[] {"id"}, "resource_index"); } @Test @@ -65,7 +65,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexProject(1); - checkTables("shouldIndexMultiModulesProject", new String[]{"id"}, "resource_index"); + checkTables("shouldIndexMultiModulesProject", new String[] {"id"}, "resource_index"); } @Test @@ -74,7 +74,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexProject(1); - checkTables("shouldReindexProjectAfterRenaming", new String[]{"id"}, "resource_index"); + checkTables("shouldReindexProjectAfterRenaming", new String[] {"id"}, "resource_index"); } @Test @@ -83,7 +83,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexProject(1); - Connection connection = getConnection().getConnection(); + Connection connection = getConnection(); ResultSet rs = null; try { // project @@ -114,7 +114,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexResource(10, "AB", Qualifiers.FILE, 3); - checkTables("empty", new String[]{"id"}, "resource_index"); + checkTables("empty", new String[] {"id"}, "resource_index"); } @Test @@ -123,7 +123,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexResource(1, "New Struts", Qualifiers.PROJECT, 1); - checkTables("shouldReindexResource", new String[]{"id"}, "resource_index"); + checkTables("shouldReindexResource", new String[] {"id"}, "resource_index"); } @Test @@ -132,6 +132,6 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { dao.indexResource(1, "Struts", Qualifiers.PROJECT, 1); - checkTables("shouldNotReindexUnchangedResource", new String[]{"id"}, "resource_index"); + checkTables("shouldNotReindexUnchangedResource", new String[] {"id"}, "resource_index"); } } diff --git a/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java b/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java index 3efe742f307..5aefd12e30b 100644 --- a/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java +++ b/sonar-core/src/test/java/org/sonar/jpa/test/AbstractDbUnitTestCase.java @@ -26,11 +26,12 @@ import org.dbunit.DatabaseUnitException; import org.dbunit.IDatabaseTester; import org.dbunit.database.DatabaseConfig; import org.dbunit.database.IDatabaseConnection; -import org.dbunit.dataset.*; +import org.dbunit.dataset.CompositeDataSet; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.ReplacementDataSet; import org.dbunit.dataset.filter.DefaultColumnFilter; import org.dbunit.dataset.xml.FlatXmlDataSet; -import org.dbunit.ext.h2.H2DataTypeFactory; -import org.dbunit.operation.DatabaseOperation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -56,41 +57,33 @@ public abstract class AbstractDbUnitTestCase { private static Database database; private static DefaultDatabaseConnector dbConnector; private static DatabaseCommands databaseCommands; - - private JpaDatabaseSession session; - private IDatabaseTester databaseTester; - private IDatabaseConnection connection; + private static IDatabaseTester databaseTester; + private static JpaDatabaseSession session; @BeforeClass - public static void startDatabase() throws Exception { - database = new H2Database(); + public static void startDatabase() { + database = new H2Database("sonarHibernate"); database.start(); dbConnector = new MemoryDatabaseConnector(database); dbConnector.start(); databaseCommands = DatabaseCommands.forDialect(database.getDialect()); - } - - @Before - public void startConnection() throws Exception { - databaseCommands.truncateDatabase(database.getDataSource().getConnection()); databaseTester = new DataSourceDatabaseTester(database.getDataSource()); session = new JpaDatabaseSession(dbConnector); session.start(); } + @Before + public void setupDbUnit() throws SQLException { + databaseCommands.truncateDatabase(database.getDataSource().getConnection()); + } + @After public void stopConnection() throws Exception { - if (databaseTester != null) { - databaseTester.onTearDown(); - } - if (connection != null) { - connection.close(); - } if (session != null) { - session.stop(); + session.rollback(); } } @@ -107,7 +100,6 @@ public abstract class AbstractDbUnitTestCase { protected DatabaseSessionFactory getSessionFactory() { return new DatabaseSessionFactory() { - public DatabaseSession getSession() { return session; } @@ -139,23 +131,30 @@ public abstract class AbstractDbUnitTestCase { } private void setupData(InputStream... dataSetStream) { + IDatabaseConnection connection = null; try { IDataSet[] dataSets = new IDataSet[dataSetStream.length]; for (int i = 0; i < dataSetStream.length; i++) { - ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(dataSetStream[i])); - dataSet.addReplacementObject("[null]", null); - dataSets[i] = dataSet; + dataSets[i] = getData(dataSetStream[i]); } - CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets); + databaseTester.setDataSet(new CompositeDataSet(dataSets)); - databaseTester.setDataSet(compositeDataSet); - connection = databaseTester.getConnection(); - - connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory()); - DatabaseOperation.CLEAN_INSERT.execute(connection, databaseTester.getDataSet()); + connection = createConnection(); + databaseCommands.getDbunitDatabaseOperation().execute(connection, databaseTester.getDataSet()); } catch (Exception e) { throw translateException("Could not setup DBUnit data", e); + } finally { + closeQuietly(connection); + } + } + + private void closeQuietly(IDatabaseConnection connection) { + try { + if (connection != null) { + connection.close(); + } + } catch (SQLException e) { } } @@ -164,44 +163,39 @@ public abstract class AbstractDbUnitTestCase { } protected void checkTables(String testName, String[] excludedColumnNames, String... tables) { - getSession().commit(); + IDatabaseConnection connection = null; try { - IDataSet dataSet = getCurrentDataSet(); + connection = createConnection(); + + IDataSet dataSet = connection.createDataSet(); IDataSet expectedDataSet = getExpectedData(testName); for (String table : tables) { ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table), excludedColumnNames); ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames); Assertion.assertEquals(filteredExpectedTable, filteredTable); } - } catch (DataSetException e) { - throw translateException("Error while checking results", e); } catch (DatabaseUnitException e) { fail(e.getMessage()); + } catch (SQLException e) { + throw translateException("Error while checking results", e); + } finally { + closeQuietly(connection); } } - /** - * Opposite of {@link #checkTables(String, String[], String...)}. - */ - protected void checkColumns(String testName, String table, String... columns) { - getSession().commit(); + private IDatabaseConnection createConnection() { try { - IDataSet dataSet = getCurrentDataSet(); - IDataSet expectedDataSet = getExpectedData(testName); - ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns); - ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns); - Assertion.assertEquals(filteredExpectedTable, filteredTable); - - } catch (DataSetException e) { - throw translateException("Error while checking columns", e); - } catch (DatabaseUnitException e) { - fail(e.getMessage()); + IDatabaseConnection connection = databaseTester.getConnection(); + connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory()); + return connection; + } catch (Exception e) { + throw translateException("Error while getting connection", e); } } private IDataSet getExpectedData(String testName) { String className = getClass().getName(); - className = String.format("/%s/%s-result.xml", className.replace(".", "/"), testName); + className = String.format("/%s/%s-result.xml", className.replace('.', '/'), testName); InputStream in = getClass().getResourceAsStream(className); try { @@ -215,20 +209,14 @@ public abstract class AbstractDbUnitTestCase { try { ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(stream)); dataSet.addReplacementObject("[null]", null); + dataSet.addReplacementObject("[false]", databaseCommands.getFalse()); + dataSet.addReplacementObject("[true]", databaseCommands.getTrue()); return dataSet; } catch (Exception e) { throw translateException("Could not read the dataset stream", e); } } - private IDataSet getCurrentDataSet() { - try { - return connection.createDataSet(); - } catch (SQLException e) { - throw translateException("Could not create the current dataset", e); - } - } - private static RuntimeException translateException(String msg, Exception cause) { RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage())); runtimeException.setStackTrace(cause.getStackTrace()); -- 2.39.5