Database Integration Testing / Unit-Testing with Spring, JPA, JUnit and Maven

The exact name for this tests is disputable. Whether it should be “database integration testing” or “unit testing”. But anyway, it is about this:
Many applications’ service layer relies heavily on database operations (through a JPA provider, for example), even though the access to the database is abstracted in a DAO layer.
An option for pure unit tests is to mock the DAO handler (using Mockito, EasyMock, etc), but in most cases this would be either a futile excercise, or it will be too complex to create well-behaving mocks.

So, using the following:
– spring 2.5.6
– hibernate entity manager
– junit 4.4
– maven2

we should achieve smooth database integration testing.
First, don’t try junit > 4.4, because spring 2.5.6 doesn’t work with it. Spring 3 will.

So, the steps.

1. define your database access properties in .properites file and place it in src/main/resources (where the applicationContext.xml should reside as well). These properties should include: the dialect, the connection url, the username/password, the database driver.
2. create src/test/resources, and create a properties file with the same name there, and set test-database parameters (using HSQLDB for example). Make the output folder for this source folder to be target/test-classes.
3. in applicationContext.xml add

<context:property-placeholder location="" />

4. in src/test/java, in an appropriate package, create the following class:


 import org.junit.runner.RunWith;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 public abstract class BaseTest {


5. Make all your test classes extend BaseTest (or alternatively, add those annotations on all classes)
6. For additional capabilities, transactions, autowiring, etc, refer to the Spring documentation
7. Run your unit tests either from within your IDE, or via maven. It works both ways.

1 thought on “Database Integration Testing / Unit-Testing with Spring, JPA, JUnit and Maven”

  1. java.lang.NoSuchMethodError: org/junit/runner/notification/RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(
    at org.junit.internal.runners.JUnit4ClassRunner$
    at org.junit.internal.runners.ClassRoadie.runUnprotected(
    at org.junit.internal.runners.ClassRoadie.runProtected(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(

    I am getting above exception. Could you pls help

Leave a Reply

Your email address will not be published.