This one had me struggling for a day before I could actually get these guys to play nicely together. So here’s the setup and what I was trying to accomplish:
- Standard maven 2 project layout
- Spring MVC + IoC
- Hibernate ORM
The project layout had the spring xml bean definitions under the WEB-INF directory. Which later proved to be a bad choice once I started writing the integration tests. Also log4j was misbehaving and not outputting any logs to the console and complaining. Well I’ll just cut to the chase and explain my setup. By the way I’m using annotated controllers and hibernate entities.
This is the directory structure from the maven project:

Place the hibernate persistence.xml file under resources/META-INF. This is crucial if you want your hibernate annotation configured entities to be picked up automatically or else you will have to manually add each one to your persistence.xml file.
Extend your test case classes from AbstractTransactionalJUnit38SpringContextTests and annotate your test case with the following annotations
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@Transactional
@ContextConfiguration("/spring/app-config.xml")
Now spring will automatically initialize the application context for you when you run your tests, and all your hibernate entities will be picked up by hibernate. This will prevent that “Unknown Entity” exception from making your life a living hell. Also make sure your entities import the javax.persistence.Entity and not the hibernate Entity annotation. This should take care of running the tests with the application context.
Sorting out the log4j is also quite simple.
Create a testing log4j configuration file called testing-log4j.xml and place it under src/test/resources. This could be a plain copy of your production log4j.xml file it doesn’t really matter. Then you have to configure maven to understand your new configuration file. Edit your pom.xml file and add this in the build section:
src/test/resources testing-log4j.xml
This will tell maven to look at the src/test/resources directory for test resources and copy them to the output directory target/ when compiling.
Next add this:
org.apache.maven.plugins maven-surefire-plugin log4j.configuration testing-log4j.xml true false
This will configure the sure-fire maven test runner plug-in and make it uses the test-log4j.xml when running tests. This will prevent your production log4j configuration from overriding your test version.