[BAEL-2749] Improves code and makes a copy in libraries-testing

This commit is contained in:
Joao Esperancinha 2020-03-31 20:18:11 +02:00
parent 906d72859f
commit 0b1c5e01a5
25 changed files with 758 additions and 95 deletions

View File

@ -1,6 +1,4 @@
### Database schema
![db schema](docs/db_schema.png)
### Relevant Articles:
- [Introduction To DBUnit](https://www.baeldung.com/dbunit)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File

@ -12,8 +12,11 @@ import org.h2.jdbcx.JdbcDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@ -24,6 +27,8 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase {
private static Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class);
@Override
protected DataSource getDataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
@ -35,9 +40,11 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase {
@Override
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(getClass()
try (InputStream resourceAsStream = getClass()
.getClassLoader()
.getResourceAsStream("data.xml"));
.getResourceAsStream("data.xml")) {
return new FlatXmlDataSetBuilder().build(resourceAsStream);
}
}
@Override
@ -76,42 +83,52 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase {
@Test
public void testEmptySchema() throws Exception {
IDataSet expectedDataSet = getDataSet();
ITable expectedTable = expectedDataSet.getTable("CLIENTS");
IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("CLIENTS");
final IDataSet expectedDataSet = getDataSet();
final ITable expectedTable = expectedDataSet.getTable("CLIENTS");
final IDataSet databaseDataSet = getConnection().createDataSet();
final ITable actualTable = databaseDataSet.getTable("CLIENTS");
Assertion.assertEquals(expectedTable, actualTable);
}
@Test
public void testAssertByQuery() throws Exception {
IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass()
try (final InputStream is = getClass()
.getClassLoader()
.getResourceAsStream("expected-user.xml"));
ITable expectedTable = expectedDataSet.getTable("CLIENTS");
Connection conn = getDataSource().getConnection();
conn.createStatement()
.executeUpdate(
"INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')");
ITable actualData = getConnection()
.createQueryTable(
"result_name",
"SELECT * FROM CLIENTS WHERE last_name='Jansen'");
Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"});
.getResourceAsStream("expected-user.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = expectedDataSet.getTable("CLIENTS");
final Connection conn = getDataSource().getConnection();
conn.createStatement()
.executeUpdate(
"INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')");
final ITable actualData = getConnection()
.createQueryTable(
"result_name",
"SELECT * FROM CLIENTS WHERE last_name='Jansen'");
Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"});
}
}
@Test(expected = AssertionError.class)
@Test
public void testMultipleFailures() throws Exception {
IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getClassLoader().getResourceAsStream("expected-multiple-failures.xml"));
ITable expectedTable = expectedDataSet.getTable("ITEMS");
Connection conn = getDataSource().getConnection();
conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')");
ITable actualData = getConnection().createDataSet().getTable("ITEMS");
DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler();
Assertion.assertEquals(expectedTable, actualData, collectingHandler);
if (!collectingHandler.getDiffList().isEmpty()) {
String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n"));
// throw new AssertionError(message);
try (final InputStream is = getClass()
.getClassLoader()
.getResourceAsStream("expected-multiple-failures.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = expectedDataSet.getTable("ITEMS");
final Connection conn = getDataSource().getConnection();
final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler();
conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')");
final ITable actualData = getConnection().createDataSet().getTable("ITEMS");
Assertion.assertEquals(expectedTable, actualData, collectingHandler);
if (!collectingHandler.getDiffList().isEmpty()) {
String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n"));
logger.error(() -> message);
}
}
}

View File

@ -31,8 +31,9 @@ public class DbUnitTest extends DBTestCase {
@Override
protected IDataSet getDataSet() throws Exception {
final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSetBuilder().build(is);
try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
@Override
@ -52,37 +53,39 @@ public class DbUnitTest extends DBTestCase {
final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1");
assertThat(rs.next()).isTrue();
assertThat(rs.getString( "title")).isEqualTo("Grey T-Shirt");
assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt");
}
@Test
public void testDelete() throws Exception {
final Connection connection = getConnection().getConnection();
final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml");
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml")) {
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
Assertion.assertEquals(expectedTable, actualTable);
Assertion.assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdate() throws Exception {
final Connection connection = getConnection().getConnection();
final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml");
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
try (final InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml")) {
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
Assertion.assertEquals(expectedTable, actualTable);
Assertion.assertEquals(expectedTable, actualTable);
}
}
}

View File

@ -42,8 +42,9 @@ public class OldSchoolDbUnitTest {
}
private static IDataSet initDataSet() throws Exception {
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSetBuilder().build(is);
try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
@Before
@ -70,78 +71,92 @@ public class OldSchoolDbUnitTest {
public void testIgnoringProduced() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final String[] excludedColumns = {"id", "produced"};
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getClassLoader()
.getResourceAsStream("expected-ignoring-registered_at.xml"));
final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns);
try (final InputStream is = getClass().getClassLoader()
.getResourceAsStream("expected-ignoring-registered_at.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns);
connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())");
connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns);
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns);
Assertion.assertEquals(expectedTable, actualTable);
Assertion.assertEquals(expectedTable, actualTable);
}
}
@Test
public void testDelete() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml");
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
try (final InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("items_exp_delete.xml");) {
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
assertEquals(expectedTable, actualTable);
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testDeleteWithExcludedColumns() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete_no_produced.xml");
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
try (final InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("items_exp_delete_no_produced.xml")) {
final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
assertEquals(expectedTable, actualTable);
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdate() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml");
final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
try (final InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("items_exp_rename.xml")) {
final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
assertEquals(expectedTable, actualTable);
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdateWithExcludedColumns() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename_no_produced.xml");
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
try (final InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("items_exp_rename_no_produced.xml")) {
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
assertEquals(expectedTable, actualTable);
assertEquals(expectedTable, actualTable);
}
}
}

View File

@ -39,8 +39,9 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
}
private IDataSet initDataSet() throws Exception {
final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSetBuilder().build(is);
try (final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
private DataFileLoader initDataFileLoader() {
@ -53,10 +54,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})};
final String[] prepDataFiles = {"/users.xml"};
final String[] expectedDataFiles = {"/users.xml"};
final PrepAndExpectedTestCaseSteps testSteps =
() -> connection
.createStatement()
.executeQuery("select * from CLIENTS where id = 1");
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeQuery("select * from CLIENTS where id = 1");
final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
@ -70,10 +69,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify
final String[] prepDataFiles = {"/users.xml"};
final String[] expectedDataFiles = {"/users_exp_rename.xml"};
final PrepAndExpectedTestCaseSteps testSteps =
() -> connection
.createStatement()
.executeUpdate("update CLIENTS set first_name = 'new name' where id = 1");
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeUpdate("update CLIENTS set first_name = 'new name' where id = 1");
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}
@ -84,10 +81,8 @@ public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})};
final String[] prepDataFiles = {"/users.xml"};
final String[] expectedDataFiles = {"/users_exp_delete.xml"};
final PrepAndExpectedTestCaseSteps testSteps =
() -> connection
.createStatement()
.executeUpdate("delete from CLIENTS where id = 2");
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeUpdate("delete from CLIENTS where id = 2");
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}

View File

@ -130,6 +130,27 @@
<version>${asciidoctor.version}</version>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>${dbunit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -150,6 +171,16 @@
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
</plugins>
</build>
@ -166,6 +197,12 @@
<spring-mock-mvc.version>4.1.1</spring-mock-mvc.version>
<assertj.version>3.6.2</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<h2.version>1.4.200</h2.version>
<dbunit.version>2.6.0</dbunit.version>
<assertj-core.version>3.14.0</assertj-core.version>
<maven-compiler-plugin.target>1.8</maven-compiler-plugin.target>
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung.dbunit;
public class ConnectionSettings {
public static final String JDBC_DRIVER = org.h2.Driver.class.getName();
public static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'";
public static final String USER = "sa";
public static final String PASSWORD = "";
}

View File

@ -0,0 +1,136 @@
package com.baeldung.dbunit;
import org.dbunit.Assertion;
import org.dbunit.DataSourceBasedDBTestCase;
import org.dbunit.assertion.DiffCollectingFailureHandler;
import org.dbunit.assertion.Difference;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL;
import static java.util.stream.Collectors.joining;
import static org.assertj.core.api.Assertions.assertThat;
public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase {
private static Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class);
@Override
protected javax.sql.DataSource getDataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL(JDBC_URL);
dataSource.setUser("sa");
dataSource.setPassword("");
return dataSource;
}
@Override
protected IDataSet getDataSet() throws Exception {
try (java.io.InputStream resourceAsStream = getClass()
.getClassLoader()
.getResourceAsStream("dbunit/data.xml")) {
return new FlatXmlDataSetBuilder().build(resourceAsStream);
}
}
@Override
protected DatabaseOperation getSetUpOperation() {
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() {
return DatabaseOperation.DELETE_ALL;
}
@Before
public void setUp() throws Exception {
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testSimpleDataSet() throws SQLException {
final Connection connection = getDataSource()
.getConnection();
final ResultSet rs = connection
.createStatement()
.executeQuery("select * from iTEMS where id = 1");
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt");
}
@Test
public void testEmptySchema() throws Exception {
final IDataSet expectedDataSet = getDataSet();
final ITable expectedTable = expectedDataSet.getTable("CLIENTS");
final IDataSet databaseDataSet = getConnection().createDataSet();
final ITable actualTable = databaseDataSet.getTable("CLIENTS");
Assertion.assertEquals(expectedTable, actualTable);
}
@Test
public void testAssertByQuery() throws Exception {
try (final java.io.InputStream is = getClass()
.getClassLoader()
.getResourceAsStream("dbunit/expected-user.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = expectedDataSet.getTable("CLIENTS");
final Connection conn = getDataSource().getConnection();
conn.createStatement()
.executeUpdate(
"INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')");
final ITable actualData = getConnection()
.createQueryTable(
"result_name",
"SELECT * FROM CLIENTS WHERE last_name='Jansen'");
Assertion.assertEqualsIgnoreCols(expectedTable, actualData, new String[]{"id"});
}
}
@Test
public void testMultipleFailures() throws Exception {
try (final java.io.InputStream is = getClass()
.getClassLoader()
.getResourceAsStream("dbunit/expected-multiple-failures.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = expectedDataSet.getTable("ITEMS");
final Connection conn = getDataSource().getConnection();
final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler();
conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')");
final ITable actualData = getConnection().createDataSet().getTable("ITEMS");
Assertion.assertEquals(expectedTable, actualData, collectingHandler);
if (!collectingHandler.getDiffList().isEmpty()) {
String message = (String) collectingHandler.getDiffList().stream().map(d -> formatDifference((Difference) d)).collect(joining("\n"));
logger.error(() -> message);
}
}
}
private static String formatDifference(Difference diff) {
return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue();
}
}

View File

@ -0,0 +1,90 @@
package com.baeldung.dbunit;
import org.dbunit.Assertion;
import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL;
import static com.baeldung.dbunit.ConnectionSettings.PASSWORD;
import static com.baeldung.dbunit.ConnectionSettings.USER;
import static org.assertj.core.api.Assertions.assertThat;
public class DbUnitTest extends DBTestCase {
public DbUnitTest(String name) {
super(name);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, JDBC_URL);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER);
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD);
}
@Override
protected IDataSet getDataSet() throws Exception {
try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
@Override
protected DatabaseOperation getSetUpOperation() {
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() {
return DatabaseOperation.DELETE_ALL;
}
@Test
public void testSelect() throws Exception {
final Connection connection = getConnection().getConnection();
final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1");
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt");
}
@Test
public void testDelete() throws Exception {
final Connection connection = getConnection().getConnection();
try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) {
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
Assertion.assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdate() throws Exception {
final Connection connection = getConnection().getConnection();
try (final java.io.InputStream is = DbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) {
ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
Assertion.assertEquals(expectedTable, actualTable);
}
}
}

View File

@ -0,0 +1,161 @@
package com.baeldung.dbunit;
import org.dbunit.Assertion;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL;
import static com.baeldung.dbunit.ConnectionSettings.PASSWORD;
import static com.baeldung.dbunit.ConnectionSettings.USER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.dbunit.Assertion.assertEquals;
public class OldSchoolDbUnitTest {
private static IDatabaseTester tester = null;
@BeforeClass
public static void setUp() throws Exception {
tester = initDatabaseTester();
}
private static IDatabaseTester initDatabaseTester() throws Exception {
final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD);
tester.setDataSet(initDataSet());
tester.setSetUpOperation(DatabaseOperation.REFRESH);
tester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
return tester;
}
private static IDataSet initDataSet() throws Exception {
try (final java.io.InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
@Before
public void setup() throws Exception {
tester.onSetup();
}
@After
public void tearDown() throws Exception {
tester.onTearDown();
}
@Test
public void testSelect() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1");
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt");
}
@Test
public void testIgnoringProduced() throws Exception {
final Connection connection = tester.getConnection().getConnection();
final String[] excludedColumns = {"id", "produced"};
try (final java.io.InputStream is = getClass().getClassLoader()
.getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) {
final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is);
final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns);
connection.createStatement().executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
final ITable actualTable = DefaultColumnFilter.excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns);
Assertion.assertEquals(expectedTable, actualTable);
}
}
@Test
public void testDelete() throws Exception {
final Connection connection = tester.getConnection().getConnection();
try (final java.io.InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("dbunit/items_exp_delete.xml");) {
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testDeleteWithExcludedColumns() throws Exception {
final Connection connection = tester.getConnection().getConnection();
try (final java.io.InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) {
final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdate() throws Exception {
final Connection connection = tester.getConnection().getConnection();
try (final java.io.InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("dbunit/items_exp_rename.xml")) {
final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
assertEquals(expectedTable, actualTable);
}
}
@Test
public void testUpdateWithExcludedColumns() throws Exception {
final Connection connection = tester.getConnection().getConnection();
try (final java.io.InputStream is =
OldSchoolDbUnitTest.class.getClassLoader()
.getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) {
ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("items");
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
assertEquals(expectedTable, actualTable);
}
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.dbunit;
import org.dbunit.DefaultPrepAndExpectedTestCase;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.PrepAndExpectedTestCaseSteps;
import org.dbunit.VerifyTableDefinition;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.dbunit.util.fileloader.DataFileLoader;
import org.dbunit.util.fileloader.FlatXmlDataFileLoader;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER;
import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL;
import static com.baeldung.dbunit.ConnectionSettings.PASSWORD;
import static com.baeldung.dbunit.ConnectionSettings.USER;
import static org.assertj.core.api.Assertions.assertThat;
public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
@Override
public void setUp() throws Exception {
setDatabaseTester(initDatabaseTester());
setDataFileLoader(initDataFileLoader());
super.setUp();
}
private IDatabaseTester initDatabaseTester() throws Exception {
final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD);
tester.setDataSet(initDataSet());
tester.setSetUpOperation(DatabaseOperation.REFRESH);
return tester;
}
private IDataSet initDataSet() throws Exception {
try (final java.io.InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) {
return new FlatXmlDataSetBuilder().build(is);
}
}
private DataFileLoader initDataFileLoader() {
return new FlatXmlDataFileLoader();
}
@Test
public void testSelect() throws Exception {
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})};
final String[] prepDataFiles = {"/dbunit/users.xml"};
final String[] expectedDataFiles = {"/dbunit/users.xml"};
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeQuery("select * from CLIENTS where id = 1");
final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
assertThat(rs.next()).isTrue();
assertThat(rs.getString("last_name")).isEqualTo("Xavier");
}
@Test
public void testUpdate() throws Exception {
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})}; // define tables to verify
final String[] prepDataFiles = {"/dbunit/users.xml"};
final String[] expectedDataFiles = {"/dbunit/users_exp_rename.xml"};
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeUpdate("update CLIENTS set first_name = 'new name' where id = 1");
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}
@Test
public void testDelete() throws Exception {
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("CLIENTS", new String[]{})};
final String[] prepDataFiles = {"/dbunit/users.xml"};
final String[] expectedDataFiles = {"/dbunit/users_exp_delete.xml"};
final PrepAndExpectedTestCaseSteps testSteps = () -> connection.createStatement()
.executeUpdate("delete from CLIENTS where id = 2");
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<CLIENTS id='1' first_name='Charles' last_name='Xavier'/>
<ITEMS id='1' title='Grey T-Shirt' price='17.99' produced='2019-03-20'/>
<ITEMS id='2' title='Fitted Hat' price='29.99' produced='2019-03-21'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='Grey T-Shirt' price='17.99' produced='2019-03-20'/>
<ITEMS id='2' title='Fitted Hat' price='29.99' produced='2019-03-21'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
<ITEMS id='6' title='Necklace' price='199.99' produced='2019-03-23'/>
</dataset>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='Grey T-Shirt' price='17.99' produced='2019-03-20'/>
<ITEMS id='2' title='Fitted Hat' price='29.99' produced='2019-03-21'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
<ITEMS id='6' title='Necklace' price='199.99' produced='2019-03-23'/>
</dataset>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<CLIENTS id='2' first_name='John' last_name='Jansen'/>
</dataset>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='Grey T-Shirt' price='17.99' produced='2019-03-20'/>
<ITEMS id='2' title='Fitted Hat' price='29.99' produced='2019-03-21'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='Grey T-Shirt' price='17.99' produced='2019-03-20'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='Grey T-Shirt' price='17.99'/>
<ITEMS id='3' title='Backpack' price='54.99'/>
<ITEMS id='4' title='Earrings' price='14.99'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='new name' price='17.99' produced='2019-03-20'/>
<ITEMS id='2' title='Fitted Hat' price='29.99' produced='2019-03-21'/>
<ITEMS id='3' title='Backpack' price='54.99' produced='2019-03-22'/>
<ITEMS id='4' title='Earrings' price='14.99' produced='2019-03-23'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<ITEMS id='1' title='new name' price='17.99'/>
<ITEMS id='2' title='Fitted Hat' price='29.99'/>
<ITEMS id='3' title='Backpack' price='54.99'/>
<ITEMS id='4' title='Earrings' price='14.99'/>
<ITEMS id='5' title='Socks' price='9.99'/>
</dataset>

View File

@ -0,0 +1,28 @@
CREATE TABLE IF NOT EXISTS CLIENTS
(
`id` int AUTO_INCREMENT NOT NULL,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS ITEMS
(
`id` int AUTO_INCREMENT NOT NULL,
`title` varchar(100) NOT NULL,
`produced` date,
`price` float,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS PURCHASES
(
`id` int NOT NULL AUTO_INCREMENT,
`id_user` int NOT NULL,
`id_item` int NOT NULL,
`total_price` float NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`id_user`) REFERENCES CLIENTS (`id`) ON DELETE CASCADE,
FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<CLIENTS id='1' first_name='Charles' last_name='Xavier'/>
<CLIENTS id='2' first_name='Scott' last_name='Summers'/>
<CLIENTS id='3' first_name='Jean' last_name='Grey'/>
</dataset>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<CLIENTS id='1' first_name='Charles' last_name='Xavier'/>
<CLIENTS id='3' first_name='Jean' last_name='Grey'/>
</dataset>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<CLIENTS id='1' first_name='new name' last_name='Xavier'/>
<CLIENTS id='2' first_name='Scott' last_name='Summers'/>
<CLIENTS id='3' first_name='Jean' last_name='Grey'/>
</dataset>