Skip to content

Commit

Permalink
Allow customizing Hibernate Configuration in DAOTest
Browse files Browse the repository at this point in the history
Closes #2053
  • Loading branch information
joschi committed Mar 10, 2018
1 parent dbfdbb2 commit 32c6f58
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
Expand Up @@ -16,6 +16,7 @@
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.function.Consumer;

public class DAOTest {
static {
Expand All @@ -33,6 +34,8 @@ public static abstract class Builder<B extends Builder<B>> {
private boolean useSqlComments = false;
private Set<Class<?>> entityClasses = new LinkedHashSet<>();
private Map<String, String> properties = new HashMap<>();
private Consumer<Configuration> configurationCustomizer = c -> {
};

public B setUrl(String url) {
this.url = url;
Expand Down Expand Up @@ -74,6 +77,11 @@ public B setProperty(String key, String value) {
return (B) this;
}

public B customizeConfiguration(Consumer<Configuration> configurationCustomizer) {
this.configurationCustomizer = configurationCustomizer;
return (B) this;
}

protected DAOTest buildDAOTest() {
final Configuration config = new Configuration();
config.setProperty(AvailableSettings.URL, url);
Expand All @@ -97,6 +105,8 @@ protected DAOTest buildDAOTest() {
entityClasses.forEach(config::addAnnotatedClass);
properties.forEach(config::setProperty);

configurationCustomizer.accept(config);

return new DAOTest(config.buildSessionFactory());
}
}
Expand Down
Expand Up @@ -2,6 +2,8 @@

import io.dropwizard.testing.app.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.junit.Rule;
import org.junit.Test;

Expand All @@ -18,15 +20,20 @@ public class DAOTestRuleConfigTest {
.setHbm2DdlAuto("create")
.setShowSql(true)
.addEntityClass(TestEntity.class)
.setProperty("hibernate.format_sql", "true")
.setProperty(AvailableSettings.FORMAT_SQL, "true")
.customizeConfiguration(c -> c.setProperty("foobar", "baz"))
.build();

@Test
public void explicitConfigCreatesSessionFactory() {
// it yields a valid SessionFactory instance
assertThat(database.getSessionFactory()).isNotNull();
final SessionFactory sessionFactory = database.getSessionFactory();
assertThat(sessionFactory).isNotNull();
assertThat(sessionFactory.getProperties())
.containsEntry(AvailableSettings.FORMAT_SQL, "true")
.containsEntry("foobar", "baz");

final Session currentSession = database.getSessionFactory().getCurrentSession();
final Session currentSession = sessionFactory.getCurrentSession();

// an instance of an entity contained in the package can be saved
currentSession.saveOrUpdate(new TestEntity("foo"));
Expand Down

0 comments on commit 32c6f58

Please sign in to comment.