[BAEL-2749] create new module `dbunit`; add DbUnit tests: `OldSchoolDbUnitTest` + `PrepAndExpectedDbUnitTest` + relevant data

This commit is contained in:
naXa! 2019-03-17 22:24:10 +03:00 committed by Joao Esperancinha
parent f79cdee39a
commit e189686b4a
15 changed files with 353 additions and 0 deletions

6
dbunit/README.md Normal file
View File

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

BIN
dbunit/docs/db_schema.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

35
dbunit/pom.xml Normal file
View File

@ -0,0 +1,35 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>dbunit</artifactId>
<version>1.0</version>
<name>dbunit</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<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>1.4.197</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<!-- testing -->
<dbunit.version>2.6.0</dbunit.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,111 @@
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.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class OldSchoolDbUnitTest {
private static final String JDBC_DRIVER = org.h2.Driver.class.getName();
private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'";
private static final String USER = "sa";
private static final String PASSWORD = "";
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.NONE);
return tester;
}
private static IDataSet initDataSet() throws Exception {
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSet(is);
}
@Before
public void setup() throws Exception {
tester.onSetup();
}
@After
public void tearDown() throws Exception {
tester.onTearDown();
}
@Test
public void testSelect() throws Exception {
// Arrange
final Connection connection = tester.getConnection().getConnection();
// Act
final ResultSet rs = connection.createStatement().executeQuery("select * from iTEMS where id = 1");
// Assert
assertTrue(rs.next());
assertEquals("Grey T-Shirt", rs.getString("title"));
}
@Test
public void testDelete() throws Exception {
// Arrange
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_delete.xml");
ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items");
//expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"});
// Act
connection.createStatement().executeUpdate("delete from ITEMS where id = 2");
// Assert
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
//actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
Assertion.assertEquals(expectedTable, actualTable);
}
@Test
public void testUpdate() throws Exception {
// Arrange
final Connection connection = tester.getConnection().getConnection();
final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("items_exp_rename.xml");
ITable expectedTable = (new FlatXmlDataSet(is)).getTable("items");
//expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"produced"});
// Act
connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1");
// Assert
final IDataSet databaseDataSet = tester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("items");
//actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"produced"});
Assertion.assertEquals(expectedTable, actualTable);
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.dbunit;
import org.dbunit.*;
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.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
public class PrepAndExpectedDbUnitTest extends DefaultPrepAndExpectedTestCase {
private static final String JDBC_DRIVER = org.h2.Driver.class.getName();
private static final String JDBC_URL = "jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'";
private static final String USER = "sa";
private static final String PASSWORD = "";
@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 {
final InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSetBuilder().build(is);
}
private DataFileLoader initDataFileLoader() {
return new FlatXmlDataFileLoader();
}
@Test
public void testSelect() throws Exception {
// Arrange
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})};
final String[] prepDataFiles = {"/users.xml"};
final String[] expectedDataFiles = {"/users.xml"};
final PrepAndExpectedTestCaseSteps testSteps = () -> {
// invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example
final ResultSet rs = connection.createStatement().executeQuery("select * from USERS where id = 1");
// either place assertions here
//assertTrue(rs.next());
//assertEquals("Xavier", rs.getString("last_name"));
return rs;
};
// Act
final ResultSet rs = (ResultSet) super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
// or place assertions at the end
assertTrue(rs.next());
assertEquals("Xavier", rs.getString("last_name"));
}
@Test
public void testUpdate() throws Exception {
// Arrange
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})}; // define tables to verify
final String[] prepDataFiles = {"/users.xml"}; // define prep files
final String[] expectedDataFiles = {"/users_exp_rename.xml"}; // define expected files
final PrepAndExpectedTestCaseSteps testSteps = () -> {
// invoke the method being tested here; for the sake of simplicity we use JDBC API directly in this example
return connection.createStatement().executeUpdate("update USERS set first_name = 'new name' where id = 1");
// after this method exits, dbUnit will:
// * verify configured tables
// * cleanup tables as configured
};
// Act
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}
@Test
public void testDelete() throws Exception {
// Arrange
final Connection connection = getConnection().getConnection();
final VerifyTableDefinition[] verifyTables = {new VerifyTableDefinition("USERS", new String[]{})};
final String[] prepDataFiles = {"/users.xml"};
final String[] expectedDataFiles = {"/users_exp_delete.xml"};
final PrepAndExpectedTestCaseSteps testSteps =
() -> connection.createStatement().executeUpdate("delete from USERS where id = 2");
// Act
super.runTest(verifyTables, prepDataFiles, expectedDataFiles, testSteps);
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<USERS 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'/>
</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='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='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,28 @@
CREATE TABLE IF NOT EXISTS USERS
(
`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 USERS (`id`) ON DELETE CASCADE,
FOREIGN KEY (`id_item`) REFERENCES ITEMS (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);

View File

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

View File

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

View File

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