Do you want to be a better Java developer? If so, check out 10 Books Every Java Developer Should Read.

Spring Data JPA Tutorial: Integration Testing

Share
Exam

Spring Data JPA makes the creation of JPA repositories extremely easy because in most cases we only have to create a special repository interface.

The big question is:

How can we write tests for our repositories because after all, they are just interfaces?

This blog post answers to that question and describes how we can write integration tests for Spring Data JPA repositories.

During this blog post we will learn to

  1. Get the required dependencies with Maven.
  2. Configure our integration tests.
  3. Write integration tests for Spring Data JPA repositories.

Let’s start by taking a quick look at our example application.

The Anatomy of Our Example Application

Our example application consists of one entity class and one repository interface.

The name of the only entity class of our example application is Todo, and its source code looks as follows:

import javax.persistence.*;

@Entity
@Table(name="todos")
public class Todo {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "description", nullable = true, length = 500)
    private String description;

    @Column(name = "title", nullable = false, length = 100)
    private String title;

    @Version
    private long version;

    public Todo() {

    }

    //Getters are omitted.
}

The name of our repository interface is TodoRepository. It has one query method which fulfills the following requirements:

  1. It must return todo entries which title or description contains the given search term.
  2. The search must be case insensitive.

The source code of the TodoRepository interface looks as follows:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface TodoRepository extends JpaRepository<Todo, Long> {

    @Query(
            "Select t FROM Todo t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :searchTerm, '%')) " +
            "OR LOWER(t.description) LIKE LOWER(CONCAT('%', :searchTerm, '%'))"
    )
    public List<Todo> search(@Param("searchTerm") String searchTerm);
}

We are now ready to get the required dependencies with Maven. Let’s see how it is done.

Getting the Required Dependencies with Maven

We can get the required dependencies with Maven by declaring the following dependencies in the pom.xml file.

  • Hamcrest All (version 1.3). We use Hamcrest to write assertions against the data returned by our repository.
  • JUnit (version 4.11). Exclude the Hamcrest core dependency.
  • Spring Test (version 3.2.3.RELEASE).
  • Spring Test DBUnit (version 1.0.0). It is used to integrate DBUnit with the Spring Test framework.
  • DBUnit (version 2.4.9). Exclude the JUnit dependency. DBUnit is used to initialize our database to a known state before our tests are executed.

The dependency declarations of our testing dependencies looks as follows:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>hamcrest-core</artifactId>
            <groupId>org.hamcrest</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.3.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.github.springtestdbunit</groupId>
    <artifactId>spring-test-dbunit</artifactId>
    <version>1.0.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.dbunit</groupId>
    <artifactId>dbunit</artifactId>
    <version>2.4.9</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>junit</artifactId>
            <groupId>junit</groupId>
        </exclusion>
    </exclusions>
</dependency>

Note: The example application has other dependencies which are not mentioned in this section. If you want to find out what these dependencies are, you should take a look at the “full” pom.xml file.

Let’s move on and configure our integration tests.

Configuring Integration Tests

We can configure our integration tests by following these steps:

  1. Configure Spring Test DBUnit.
  2. Configure the integration tests.

These steps are described with more details in the following subsections.

Configuring Spring Test DBUnit

We can configure Spring Test DBUnit by following these steps:

  1. Configure a DataSource bean in the application context configuration class or in the application context configuration file.
  2. Configure the actual test class.

These steps are described with more details in the following.

Configuring the DataSource Bean

We can configure the DataSource bean by using either a Java configuration class or a XML configuration file. Let’s start by creating a properties file called application.properties. This file contains the configuration of the used database connection.

The content of the application.properties file looks as follows:

#Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:mem:datajpa
db.username=sa
db.password=

If we want to use a Java configuration class, we can configure the DataSource bean by following these steps:

  1. Annotate the configuration class with the @Configuration annotation.
  2. Annotate the configuration class with the @PropertySource annotation. Configure that properties are loaded from a properties file called application.properties which is found from the classpath.
  3. Add an Environment field to the configuration class and annotate the field with the @Autowired annotation.
  4. Add a public DataSource dataSource() method the configuration class and annotate it with the @Bean annotation.
  5. Implement the dataSource() method. We can do this by creating a new BoneCPDataSource object, configuring the used database connection, and returning the created object.

The source code of our application context configuration class looks as follows:

import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:application.properties")
public class PersistenceContext {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();

        dataSource.setDriverClass(environment.getRequiredProperty("db.driver"));
        dataSource.setJdbcUrl(environment.getRequiredProperty("db.url"));
        dataSource.setUsername(environment.getRequiredProperty("db.username"));
        dataSource.setPassword(environment.getRequiredProperty("db.password"));

        return dataSource;
    }

    //Other beans are omitted.
}

If we want to use a XML configuration file, we can configure the DataSource bean by following these steps:

  1. Create a new PropertyPlaceHolderConfigurer by using the property-placeholder element of the context namespace. Ensure that the properties are loaded from a properties file called application.properties which is found from the classpath.
  2. Configure a dataSource bean by using the bean element of the beans namespace. Set the value of class attribute to com.jolbox.bonecp.BoneCPDataSource.
  3. Configure the database connection.

The content of our application context configuration file looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:jpa="http://www.springframework.org/schema/data/jpa"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">


    <context:property-placeholder location="classpath:application.properties" ignore-resource-not-found="false"/>

    <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
        <property name="driverClass" value="${db.driver}"/>
        <property name="jdbcUrl" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>
</beans>

We have now configured the DataSource bean required by Spring Test DBUnit. Let’s move on and configure our test class.

Configuring the Test Class

We can add the Spring Test DBUnit configuration to a test class by following these steps:

  1. Annotate the test class with the @TestExecutionListeners annotation.
  2. Pass the standard Spring listeners and the DBUnitTestExecutionListener as the value of the @TestExecutionListeners annotation. The DBUnitTestExecutionListener ensures that Spring process the DBUnit annotations found from our test classes.

After we have added the Spring Test DBUnit configuration to our test class, its source code looks as follows:

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;

@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
public class ITTodoRepositoryTest {

}

Configuring the Actual Tests

We can configure our integration tests by following these steps:

  1. Ensure that the SpringJUnit4ClassRunner is used to run our integration tests.
  2. Configure the used application context configuration class or file by using the @ContextConfiguration annotation.
  3. Configure Spring Test DBUnit by following the approach described earlier.
  4. Add a TodoRepository field to the test class and annotate the field with the @Autowired annotation.

That is it. We have now configured our integration test. The source code of our test class looks as follows:

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
//@ContextConfiguration(locations = {"classpath:exampleApplicationContext-persistence.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
public class ITTodoRepositoryTest {
   
    @Autowired
    private TodoRepository repository;
}

Let’s move on and write some integration tests to our repository.

Writing Integration Tests

We can write integration tests for our repository by following these steps:

  1. Configure the DBUnit dataset which is used to initialize our database to a known state before our tests are run.
  2. Write the actual integration tests.

These steps are described with more details in the following.

Configuring the Used DBUnit Dataset

We can configure the DBUnit dataset which is used to initialize our database to a known state before each test case is executed by using the @DatabaseSetup annotation and setting the name of the DBUnit dataset file as its value.

We can add the @DatabaseSetup annotation either to a class or to a test method. The difference between these two scenarios is described in the following:

  • If we add the @DatabaseSetup annotation to a class, the same dataset is used to iniatilize the database to a known state before each test method.
  • If we want to use different datasets in different tests, we must add the @DatabaseSetup annotation to our test methods.

In our case, we will use the same dataset in every test. Thus, we can configure the used dataset by adding the @DatabaseSetup annotation to our test class.

The source code of our test class looks as follows:

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
//@ContextConfiguration(locations = {"classpath:exampleApplicationContext-persistence.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
@DatabaseSetup("toDoData.xml")
public class ITTodoRepositoryTest {
   
    @Autowired
    private TodoRepository repository;
}

The content of the toDoData.xml file looks as follows:

<dataset>
    <todos id="1" description="Lorem ipsum" title="Foo" version="0"/>
    <todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>

Enough with theory. Let’s write some tests.

Writing the Actual Integration Tests

Our last task is to write integration tests for our Spring Data JPA repository. When we are writing tests for a data access layer which uses relational database, we should follow these principles:

  • We should not write tests for methods provided by the used persistence framework. There are of course exceptions to this rule. One such exception is a situation where we we need to test that a database trigger is working correctly when new data is added to the database or existing data is updated to the database. Antti Koivisto has written a great blog post about testing database triggers. Check it out if you are interested about this.
  • We should write tests which ensure that each database query which is created by us is returning the correct data.
  • Follow the best practices of DBUnit.

Thus, we have to write three integration tests for our repository:

  1. We have to write an integration test which ensures that when no todo entries are found, an empty list is returned.
  2. We have write an integration test which verifies that when a title of a single todo entry matches with the given search term, our repository returns a list which contains one todo entry.
  3. We have to write an integration test which verifies that when the description of two todo entries matches with the given search term, our repository returns a list which contains two todo entries.

Let’s get started.

No Results Found

We can write the first integration test by following these steps:

  1. Call the search() method of the TodoRepository interface and pass a search term which is not from the dataset file as a method parameter.
  2. Verify that the returned list is empty.

The source code of the first integration test looks as follows:

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

//Configuration is omitted.
public class ITTodoRepositoryTest {

    @Autowired
    private TodoRepository repository;

    @Test
    public void search_NoTodoEntriesFound_ShouldReturnEmptyList() {
        List<Todo> todoEntries = repository.search("NOT FOUND");
        assertThat(todoEntries.size(), is(0));
    }
}

The Title of a Single Todo Entry Matches with the Search Term

We can write the second integration test by following these steps:

  1. Call the search() method of the TodoRepository interface and pass a string ‘foo’ as a method parameter.
  2. Verify that returned list contains one todo entry.
  3. Ensure that the list contains the correct todo entry.

The source code of our second integration test looks as follows:

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;

//Configuration is omitted
public class ITTodoRepositoryTest {

    @Autowired
    private TodoRepository repository;

    @Test
    public void search_OneTodoEntryFound_ShouldReturnAListOfOneEntry() {
        List<Todo> todoEntries = repository.search("foo");

        assertThat(todoEntries.size(), is(1));
        assertThat(todoEntries.get(0), allOf(
                hasProperty("id", is(1L)),
                hasProperty("title", is("Foo")),
                hasProperty("description", is("Lorem ipsum"))
        ));
    }
}

The Description of Two Todo Entries Matches with the Search Term

We can write the third integration test by following these steps:

  1. Call the search() method of the TodoRepository interface and pass a string ‘Ips’ as a method parameter.
  2. Verify that the returned list contains two todo entries.
  3. Verify that the list contains only those todo entries whose description matches the given search term.

The source code of the third integration test looks as follows:

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;

//Configuration is omitted
public class ITTodoRepositoryTest {

    @Autowired
    private TodoRepository repository;

    @Test
    public void search_TwoTodoEntriesFound_ShouldReturnAListOfTwoEntries() {
        List<Todo> todoEntries = repository.search("Ips");

        assertThat(todoEntries.size(), is(2));
        assertThat(todoEntries, contains(
                allOf(
                        hasProperty("id", is(1L)),
                        hasProperty("title", is("Foo")),
                        hasProperty("description", is("Lorem ipsum"))
                ),
                allOf(
                        hasProperty("id", is(2L)),
                        hasProperty("title", is("Bar")),
                        hasProperty("description", is("Lorem ipsum"))
                )
        ));
    }
}

Summary

We have now written integration tests for our Spring Data JPA repository. This blog post has taught us four things:

  1. We learned what kind of tests we should write for our repositories.
  2. We learned to configure Spring Test DBUnit.
  3. We learned to integrate DBUnit with the Spring Test Framework.
  4. We learned to use Hamcrest matchers for ensuring that the data returned by our repository is correct.

The example application of this blog post is available at Github.

If you enjoy reading similar content, you should follow me on Twitter:

About the Author

Petri Kainulainen is passionate about software development and continuous improvement. He specializes in software development with the Spring Framework and is the author of Spring Data book.

About Petri Kainulainen →

26 comments… add one

  • I got java.lang.NullPointerException when I attemt to run repository method ,
    object who insance of interface is null .
    How solve it ?

    Reply
  • This tutorial helped me and my team implement unit tests successfully. There are minor things missing in the post (like bonecp inclusion in the pom.xml and the full contents of the Spring context) but the github project helped to fill those.

    Great work and thanks for sharing!

    Reply
    • I am happy to hear that your team found this blog post useful. Also, I left the other dependencies out because I felt that they were out of the scope of this post. However, now that you mentioned this issue, I will update this blog post and add a link to the full pom.xml file. Maybe this will clarify things a bit.

      Reply
  • the useful article, thanks!!

    Reply
    • You are welcome. I am happy to hear that this blog post was useful to you.

      Reply
  • Hi Petri

    Im trying to use spring db unit. The versions I have are the ones recommended above in your blog. However Im encountering (could not find dataset.xml) file
    testController(my.tests.web.TermControllerIntegrationTest) Time elapsed: 4.245 sec <<< ERROR!
    java.lang.IllegalArgumentException: Unable to load dataset from "classpath:/termData.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader
    at org.springframework.util.Assert.notNull(Assert.java:112)

    I have tried many things.
    Putting the dataset in the same package as the class.
    in the classpath under resources
    and trying to reference it with'/' like classpath:/termData.xml etc with no luck.
    My unit test works well without db unit.

    @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    //TransactionDbUnitTestExecutionListener.class})
    DbUnitTestExecutionListener.class })

    any help would be very useful.

    Reply
    • Hi Chris,

      If the dataset file is in the same package than your test class, you can reference it by simply using its name (In your case, termsData.xml should work). Also, remember that you have to compile your project every time when you add a new dataset file or modify an existing file (this sucks btw).

      Reply
  • Can you give me an example to write @Query for Join operation ? Iam struggling with the error called “unexpected token:” error – @Query(select count(*) from employee emp join employeedetaildata edd on emp.id=edd.employeedataid where emp.rankId = :rankId)

    Reply
  • Hi Petri,

    thanks for your great Spring Data JPA tutorials. I just started to use DbUnit in one of my private applications but I get this warning every time DbUnit sets up the database via @DatabaseSetup:

    WARN org.dbunit.dataset.AbstractTableMetaData – Potential problem found: The configured data type factory ‘class org.dbunit.dataset.datatype.DefaultDataTypeFactory’ might cause problems with the current database ‘H2′ (e.g. some datatypes may not be supported properly). In rare cases you might see this message because the list of supported database products is incomplete (list=[derby]). If so please request a java-class update via the forums.If you are using your own IDataTypeFactory extending DefaultDataTypeFactory, ensure that you override getValidDbProducts() to specify the supported database products.

    Relevant test dependencies:
    org.springframework:spring-test:4.0.2
    com.github.springtestdbunit:spring-test-dbunit:1.1.0
    org.dbunit:dbunit:2.4.9
    com.h2database:h2:1.3.175

    The only difference to your setup is, that I override the DataSource of my default application config in the test config via:

    @Bean
    public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }

    But that should not be the problem. I am able to suppress the warning via logging configuration but maybe you know another way to solve this “problem” (all test run fine)?

    Best regards,
    Patrick

    P.S.: Have you already recognized the new Hikari Connection Pool (HikariCP) as alternate to BoneCP? Though I haven’t benchmarked the connection pool myself yet, it definitely feels faster than BoneCP to me and the benchmarks on the HikariCP web page promise an outstanding performance.

    Reply
    • Hi Patrick,

      Thank you for your kind words! It is nice to hear that my tutorials have been useful to you.

      I assume that this line is written to the log because the default DbUnit data type factory doesn’t support vendor specific data types. I am not 100% sure about this but it seems like a reasonable assumption (my assumption is based on this DbUnit FAQ entry).

      If my assumption is correct, you have to configure DbUnit to use the H2DataTypeFactory instead of the DefaultDataTypeFactory. When you use Spring Test DBUnit, you can do this adding the DatabaseConfigBean (configure the data type factory by calling the setDatatypeFactory() method) and DatabaseDataSourceConnectionFactoryBean beans to the application context (more about this here. Search for Custom IDatabaseConnections text).

      I haven’t done this myself because I haven’t been using vendor specific data types but based on the documentation, it should do the trick. By the way, I figured this out after I read this answer to a similar Stack Overflow question.

      I haven’t used HikariCP myself but I ran its data source benchmark this week, and HikariCP seems to be a lot faster than BoneCP. I am going to try it in the example applications of my new blog entries. It will be interesting to see if I notice any difference.

      Reply
      • Hi Petri,

        thanks for your quick reply. I solved the warning by using this configuration: https://gist.github.com/PatrickGotthard/9558923

        Regards,
        Patrick

        Reply
        • Hi Patrick,

          you are welcome. Your configuration looks simple and I am going to use the same approach in my new blog posts. Thanks for sharing it.

          Reply
          • Hi again,

            are you interested to be notified when I push the project to GitHub? Maybe we could exchange some knowledge based on the projects sources.

          • Hi,

            sure. Let me know when you do that (push the project to Github). I think it would be a good opportunity to learn something new (for both of us).

          • Hi Petri,

            I have pushed my project to GitHub now: https://github.com/PatrickGotthard/newsreadr-server

            Feel free to look at the sources (especially the integration tests). I would be really happy to get some input from you.

            You would have to check out https://github.com/PatrickGotthard/newsreadr-bom and https://github.com/PatrickGotthard/newsreadr-shared as well to import the project into your IDE (currently there are no public Maven snapshots available but I would configure my Jenkins and Nexus soon).

            Regards,
            Patrick

          • Hi Patrick,

            Cool! I will take a look at that project later this week (and give feedback of course).

          • Update: the transitive dependencies are now public available so that you don’t have to check out the related projects. I’ve also added installation and build instructions to get started.

          • I just cloned the Github repository and started playing with the code. I will email my thoughts to you when I am finished.

  • nice post, would i ask for an example on how to test model data ?
    I want to test a controller request method that initiate the model data,
    also is it possible to test thymeleaf templates ?

    Thanks in advance

    Reply
    • You should check out my Spring MVC Test Tutorial. It explains how you can write both unit and integration tests for your Spring MVC controllers.

      Also, It is possible to test Thymeleaf templates by using the Spring MVC Test framework. I haven’t written anything about this because I haven’t had the chance to use Thymeleaf. However, this blog post has a small description about this, and it seems that writing tests for Thymeleaf templates is pretty simple. All you have to do is to write assertions for the response body.

      Reply
  • Very great blog. Good explanation.
    Thank you!

    Reply
    • You are welcome. I am happy to hear that this blog post was useful to you.

      Reply
  • Nice post. Can I ask : How can I write integration test cases (testing from request to response) on my spring mvc app which uses spring data jpa – without changing the state of the oracle database ? Can I somehow fetch the required tables and their data into an in memory database for testing purposes ?
    I have never used it but DBUnit seems less configurable for complex data sets and I don’t want to write xml files for data sets. AND it doesn’t create in memory HSQLDB tables either. What other options do I have ?

    Reply
    • The example application of this blog has two profiles: dev and integration-test. Both of these profiles use H2 in-memory database but in a real life scenario, only the integration-test profile would be using it (the other profiles would use a “real” database).

      I have configured Hibernate to create the database tables by setting the value of the hibernate.hbm2ddl.auto property to create-drop.

      If you take a look at the config.properties file used when the integration-test Maven profile is activated, you will find the following line from it:

      
      hibernate.hbm2ddl.auto=create-drop
      
      

      This line ensures that the Hibernate creates the database for my integration tests. After the database has been created, I insert the test data by using DbUnit. All example applications of my Spring MVC Test tutorial use the same approach.

      I agree that the DbUnit can be a tricky beast to configure and large data sets are pain in the ass (that is why they should be avoided). However, I haven’t been able to find any alternatives to it. If you happen to find one, let me know!

      Reply

Leave a Comment