Skip to content

Commit

Permalink
refs #55
Browse files Browse the repository at this point in the history
  • Loading branch information
rmpestano committed Sep 14, 2016
1 parent 9196c04 commit 24887d8
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import com.github.dbunit.rules.configuration.DataSetConfig;
import com.github.dbunit.rules.exception.DataBaseSeedingException;
import com.github.dbunit.rules.replacer.DateTimeReplacer;
import com.github.dbunit.rules.util.DriverUtils;
import com.github.dbunit.rules.replacer.ScriptReplacer;
import com.github.dbunit.rules.util.DriverUtils;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.AmbiguousTableNameException;
import org.dbunit.database.DatabaseConfig;
Expand Down
23 changes: 21 additions & 2 deletions junit5/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
Expand Down Expand Up @@ -84,17 +96,23 @@
<encoding>UTF-8</encoding>
</configuration>
</plugin>



<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<includes>
<include>**/Test*.java</include>
<include>**/*It.java</include>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
<include>**/*TestCase.java</include>
</includes>
<systemPropertyVariables>
<java.util.logging.config.file>
src/test/resources/logging.properties
</java.util.logging.config.file>
</systemPropertyVariables>
</configuration>
<dependencies>
<dependency>
Expand All @@ -103,6 +121,7 @@
<version>1.0.0-M2</version>
</dependency>
</dependencies>

</plugin>

</plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,36 +64,54 @@ public void beforeTestExecution(TestExtensionContext testExtensionContext) throw
annotation = testExtensionContext.getTestClass().get().getAnnotation(DataSet.class);
}

if (annotation == null) {
throw new RuntimeException("Could not find DataSet annotation for test " + testExtensionContext.getTestMethod().get().getName());
}

DBUnitConfig dbUnitConfig = DBUnitConfig.from(testExtensionContext.getTestMethod().get());
final DataSetConfig dasetConfig = new DataSetConfig().from(annotation);
final DataSetConfig dataSetConfig = new DataSetConfig().from(annotation);
if(connectionHolder == null || connectionHolder.getConnection() == null){
connectionHolder = createConnection(dbUnitConfig,testExtensionContext.getTestMethod().get().getName());
}
DataSetExecutor executor = DataSetExecutorImpl.instance(dasetConfig.getExecutorId(), connectionHolder);
DataSetExecutor executor = DataSetExecutorImpl.instance(dataSetConfig.getExecutorId(), connectionHolder);
executor.setDBUnitConfig(dbUnitConfig);



if (dataSetConfig != null && dataSetConfig.getExecuteStatementsBefore() != null && dataSetConfig.getExecuteStatementsBefore().length > 0) {
try {
executor.executeStatements(dataSetConfig.getExecuteStatementsBefore());
} catch (Exception e) {
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute statements Before:" + e.getMessage(), e);
}
}//end execute statements

if (dataSetConfig.getExecuteScriptsBefore() != null && dataSetConfig.getExecuteScriptsBefore().length > 0) {
try {
for (int i = 0; i < dataSetConfig.getExecuteScriptsBefore().length; i++) {
executor.executeScript(dataSetConfig.getExecuteScriptsBefore()[i]);
}
} catch (Exception e) {
if (e instanceof DatabaseUnitException) {
throw e;
}
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute scriptsBefore:" + e.getMessage(), e);
}
}//end execute scripts

ExtensionContext.Namespace namespace = getExecutorNamespace(testExtensionContext);//one executor per test class
testExtensionContext.getStore(namespace).put(EXECUTOR_STORE, executor);
testExtensionContext.getStore(namespace).put(DATASET_CONFIG_STORE, dasetConfig);
testExtensionContext.getStore(namespace).put(DATASET_CONFIG_STORE, dataSetConfig);
if (dbUnitConfig.isLeakHunter()) {
LeakHunter leakHunter = LeakHunterFactory.from(connectionHolder.getConnection());
testExtensionContext.getStore(namespace).put(LEAK_STORE, leakHunter);
testExtensionContext.getStore(namespace).put(CONNECTION_BEFORE_STORE, leakHunter.openConnections());
}

try {
executor.createDataSet(dasetConfig);
executor.createDataSet(dataSetConfig);
} catch (final Exception e) {
throw new RuntimeException(String.format("Could not create dataset for test method %s due to following error " + e.getMessage(), testExtensionContext.getTestMethod().get().getName()), e);
}

boolean isTransactional = dasetConfig.isTransactional();
boolean isTransactional = dataSetConfig.isTransactional();
if (isTransactional) {
if (isEntityManagerActive()) {
em().getTransaction().begin();
Expand Down Expand Up @@ -195,18 +213,13 @@ public void afterTestExecution(TestExtensionContext testExtensionContext) throws
exportDataSet(executor,testExtensionContext.getTestMethod().get());
}

if (dataSetConfig.getExecuteStatementsAfter() != null && dataSetConfig.getExecuteStatementsAfter().length > 0) {
if (dataSetConfig != null && dataSetConfig.getExecuteStatementsAfter() != null && dataSetConfig.getExecuteStatementsAfter().length > 0) {
try {
for (int i = 0; i < dataSetConfig.getExecuteScriptsAfter().length; i++) {
executor.executeScript(dataSetConfig.getExecuteScriptsAfter()[i]);
}
executor.executeStatements(dataSetConfig.getExecuteStatementsAfter());
} catch (Exception e) {
if (e instanceof DatabaseUnitException) {
throw e;
}
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute scriptsAfter:" + e.getMessage(), e);
LoggerFactory.getLogger(getClass().getName()).error(testExtensionContext.getTestMethod().get().getName() + "() - Could not execute statements after:" + e.getMessage(), e);
}
}//end execute scripts
}//end execute statements

if (dataSetConfig.getExecuteScriptsAfter() != null && dataSetConfig.getExecuteScriptsAfter().length > 0) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.github.dbunit.rules.api.dataset.DataSet;
import com.github.dbunit.rules.api.dataset.ExpectedDataSet;
import com.github.dbunit.rules.junit5.model.User;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
Expand All @@ -29,10 +29,12 @@ public class DBUnitJUnit5It {
//DBUnitExtension will get connection by reflection so either declare a field or a method with ConncetionHolder as return type
//tag::connectionField[]
private ConnectionHolder connectionHolder = () -> //<3>
instance("junit5-pu").connection();//<4>
instance("junit5-pu").clear().connection();//<4>

//end::connectionField[]



//tag::test[]
@Test
@DataSet("users.yml")
Expand Down Expand Up @@ -93,4 +95,26 @@ public User getUser(Long id){
return (User) em().createQuery("select u from User u where u.id = :id").
setParameter("id", id).getSingleResult();
}

@Test
@DataSet(value = "usersWithTweet.yml", executeStatementsBefore = "SET DATABASE REFERENTIAL INTEGRITY FALSE;", executeStatementsAfter = "SET DATABASE REFERENTIAL INTEGRITY TRUE;")
public void shouldSeedDataSetDisablingContraintsViaStatement() {
User user = (User) em().createQuery("select u from User u join fetch u.tweets where u.id = 1").getSingleResult();
assertThat(user).isNotNull();
assertThat(user.getId()).isEqualTo(1);
assertThat(user.getTweets()).hasSize(1);
}



@Test
@DataSet(value = "usersWithTweet.yml",
useSequenceFiltering = false,
tableOrdering = {"USER","TWEET"},
executeStatementsBefore = {"DELETE FROM TWEET","DELETE FROM USER"}
)
public void shouldSeedDataSetUsingTableCreationOrder() {
List<User> users = em().createQuery("select u from User u left join fetch u.tweets").getResultList();
assertThat(users).hasSize(2);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
*/
@ExtendWith(DBUnitExtension.class)
@RunWith(JUnitPlatform.class)
@DBUnit(url = "jdbc:hsqldb:mem:flyway;DB_CLOSE_DELAY=-1", driver = "org.hsqldb.jdbcDriver", user = "sa")
@DBUnit(cacheConnection=false,cacheTableNames = false, url = "jdbc:hsqldb:mem:flyway;DB_CLOSE_DELAY=-1", driver = "org.hsqldb.jdbcDriver", user = "sa")
public class FlywayIt {

private static Flyway flyway;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
public class ScriptsIt {

private ConnectionHolder connectionHolder = () ->
instance("junit5-pu").connection();
instance("junit5-pu").clear().connection();

@BeforeAll
public static void before() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package com.github.dbunit.rules.junit5.model;

import javax.persistence.*;
import javax.validation.constraints.Size;

import org.hibernate.annotations.GenericGenerator;

import java.util.Calendar;

/**
* Created by pestano on 22/07/15.
*/
@Entity
public class Tweet {

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

@Size(min = 1, max = 140)
private String content;

private Integer likes;

@Temporal(TemporalType.TIMESTAMP)
private Calendar date;

@ManyToOne
User user;

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public Integer getLikes() {
return likes;
}

public void setLikes(Integer likes) {
this.likes = likes;
}


public Calendar getDate() {
return date;
}

public void setDate(Calendar date) {
this.date = date;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Tweet tweet = (Tweet) o;

return !(id != null ? !id.equals(tweet.id) : tweet.id != null);

}

@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;

/**
* Created by pestano on 22/07/15.
Expand All @@ -16,6 +18,9 @@ public class User {

private String name;

@OneToMany(mappedBy = "user")
private List<Tweet> tweets;


public User() {
}
Expand Down Expand Up @@ -45,6 +50,14 @@ public void setId(long id) {
this.id = id;
}

public List<Tweet> getTweets() {
return tweets;
}

public void setTweets(List<Tweet> tweets) {
this.tweets = tweets;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
Expand Down
3 changes: 2 additions & 1 deletion junit5/src/test/resources/META-INF/persistence.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

<class>com.github.dbunit.rules.junit5.model.User</class>
<class>com.github.dbunit.rules.junit5.model.Tweet</class>


<properties>
Expand All @@ -14,7 +15,7 @@
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>

</persistence-unit>
Expand Down
10 changes: 10 additions & 0 deletions junit5/src/test/resources/datasets/usersWithTweet.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
user:
- id: 1
name: "@realpestano"
- id: 2
name: "@dbunit"
tweet:
- id: abcdef12345
content: "dbunit rules!"
date: "[DAY,NOW]"
user_id: 1
7 changes: 7 additions & 0 deletions junit5/src/test/resources/logging.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
handlers = java.util.logging.ConsoleHandler


java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter

com.github.dbunit.rules.level=FINE

Loading

0 comments on commit 24887d8

Please sign in to comment.