Anantha Krishnan
Anantha Krishnan

Reputation: 3088

JUnit 4 - create HSQLDB tables programmatically before running unit tests

I am using HSQLDB for unit testing, I have bunch of Test classes which all extends one Abstract class MyAbstractTestBase.

class abstract MyAbstractTestBase 
{
   static
   {
      setUpDBTables();
   }

   public static void setUpDBTables()
   {
        context = new ClassPathXmlApplicationContext(new String[]{
            "file:spring-configuration/unit-testing-config.xml"
        });
        //InputStream inputStream = getClass().getClassLoader().getResourceAsStream("db/MY_TABLE.sql");
        DataSource dataSource = (DataSource)context.getBean("MyDataSource");

        namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

   }
}

Major problem with this approach is entityManager created by spring,

@PersistenceContext(unitName = MyConstants.ENTITY_MANAGER_FACTORY_UNIT_NAME)
protected EntityManager entityManager;

doesn't persist data and no exception is thrown either, but if I try to read some data using "select" it works.

Here is my question, How do I create tables before starting unit-tests? So that my entityManager will work as expected.

Also, why did my entityManager did not persist any record even though it did not throw any exception.

Upvotes: 0

Views: 2039

Answers (1)

Kkkev
Kkkev

Reputation: 4925

If you're using spring test, I strongly suggest using the approach from this answer: How to load DBUnit test data once per case with Spring Test

Upvotes: 1

Related Questions