JUnit Testing Spring Service and DAO (with In-Memory Database)

This post describes how to implement JUnit tests for a Spring Web Application’s Services and DAO. It is built on top of the Spring MVC-Service-DAO-Persistence Architecture Example. This example is available from Github in the Spring-Web-JPA-Testing directory.


  • Test Fixture – The fixed state used as a baseline for running tests.
  • Unit test – These tests verify that pieces of code (components) perform some functionalities as expected. In a Java environment, these are typically implemented at the class level.
  • Integration test – Integration testing is any type of test checking that a set of interacting components perform expected functionalities together correctly.


We need a JPA Hibernate configuration for in-memory testing:

public class JpaTestConfig {

    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setPackagesToScan(new String[] {'com.jverstry'});

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();

        Properties ps = new Properties();
        ps.put('hibernate.dialect', 'org.hibernate.dialect.HSQLDialect');
        ps.put('hibernate.hbm2ddl.auto', 'create');


        return lcemfb;


    public DataSource dataSource(){

        DriverManagerDataSource ds = new DriverManagerDataSource();


        return ds;


    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

            this.entityManagerFactoryBean().getObject() );

        return tm;


    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();


We need to exclude the production configuration from package scanning (no ‘com.jverstry’ scanning):

@ComponentScan(basePackages = {

public class TestConfig {

    public MyService getMyService() {
        return new MyServiceImpl();


Spring Testing Tools

  • @RunWith – This is a JUnit annotation allowing one to run a test with a different runner than the one provided by JUnit.
  • SpringJUnit4ClassRunner – This is a JUnit test runner for Spring applications. Typically, test classes are annoted with @RunWith(SpringJUnit4ClassRunner.class).
  • @ContextConfiguration – This annotation can be used to specify how to load an applicationContext in Spring test class. This can be configured via XML files or Java configuration objects.

Service Testing

The following class tests the createAndRetrieve() method of our injected MyService implementation:

@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyServiceImplTest {

    private MyService myService;

    public void testCreateAndRetrieve() {

        MilliTimeItem retr = myService.createAndRetrieve();




DAO Testing

The following class tests our DAO implementation. Our implementation is injected with an EntityManager created from our test configuration class defined above.

@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyPersistenceDAOTest {

    private MyPersistenceDAO myDAO;

    public void testCreateMilliTimeItem() {

        // This operation should not throw an Exception
        long id = myDAO.createMilliTimeItem();


    public void testGetMilliTimeItem() {

        long id = myDAO.createMilliTimeItem();
        MilliTimeItem retr = myDAO.getMilliTimeItem(id);





When starting to write JUnit tests for Spring, one can come across the following error messages:

Absent Code attribute in method that is not native or abstract in class file javax/validation/Validation

The above is often caused by the following maven dependency:


It should be replaced with:


Another error message is:

javax.validation.ValidationException: Unable to find a default provider

This is solved by adding the following maven dependency:


More Spring related posts here.

Reference: JUnit Testing Spring Service and DAO (with In-Memory Database) from our JCG partner Jerome Versrynge at the Technical Notes blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

One Response to "JUnit Testing Spring Service and DAO (with In-Memory Database)"

  1. Nir M says:

    Cool.You can also check out the following for “how to” JUnit tests + JPA + XML based Spring configuration:

Leave a Reply

4 + four =

Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: