Tag Archives: spring framwork

Unit Testing Using In-Memory MySQL Database On Spring

Well the title lied, there’s no such thing as in-memory MySQL database (or at least I won’t be using it for this article). Instead I will use H2 in-memory database setup to run in “MySQL mode”


  
  

(thanks to joensson for sharing this technique on SO)

If your app just uses plain jdbc then adding above datasource to your test context would be sufficient, but if you use JPA/Hibernate the cost of table setup, scanning etc could be quite significant.

To overcome this you can split the test context using y annotation.

In the example below I have unit tests for two DAOs: AccountDAOTest and CustomerDAOTest:

y({
  ation("/test-root-context.xml"),
  ation("AccountDAOTest-context.xml")
})
(SpringJUnit4ClassRunner.class)
public class AccountDAOTest {
}
y({
  ation("/test-root-context.xml"),
  ation("CustomerDAOTest-context.xml")
})
(SpringJUnit4ClassRunner.class)
public class CustomerDAOTest {
}

By doing this Spring test-root-context.xml will be setup once and reused accross all unit tests. Only put components common to all tests in test-root-context.xml. In my case I put the following:

  • DataSource
  • EntityManagerFactory
  • TransactionManager


  
  





  
  




  

All test specific components go into their respective context.

Don’t forget to add if your DAO uses it. This can’t be placed on test-root-context.xml because I don’t scan all my DAOs there.

And lastly — ofcourse — you need to make sure your pom.xml has dependency to spring-test, junit and h2



  com.h2database
  h2
  1.3.176
  test



  org.springframework
  spring-test
  ${org.springframework-version}
  test



  junit
  junit
  4.7
  test