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.
- 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.
- 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.
- in applicationContext.xml add
<context:property-placeholder location="classpath:application.properties" />
- in src/test/java, in an appropriate package, create the following class:
package com.tickets; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:/applicationContext.xml") public abstract class BaseTest { } - Make all your test classes extend BaseTest (or alternatively, add those annotations on all classes)
- For additional capabilities, transactions, autowiring, etc, refer to the Spring documentation
- Run your unit tests either from within your IDE, or via maven. It works both ways.
June 19, 2012 at 2:58 pm |
[...] A article for Database integration testing / unit-testing with Spring, JPA, JUnit and Maven Like this:LikeBe the first to like this. [...]