Question

Goal

In order to test the create method of a DAO, I create an instance, insert it in database, flush the entity manager to update the database and then use dbunit to compare table using dataset.


Code

Here is the code, it uses Spring test, DBUnit and JPA (via Hibernate) :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "/WEB-INF/applicationContext-database.xml"})
public class MyEntityTest extends AbstractTransactionalJUnit4SpringContextTests {

    @PersistenceContext
    protected EntityManager em;

    @Autowired
    MyEntityDAO myEntityDAO;

    @Test
    public void createTest() {
        // create the entity
        MyEntity record = new MyEntity();
        record.setData("test");    
        myEntityDAO.insertNew(record);

        // flush to update the database
        em.flush();         

        // get actual dataset from the connection
        Session session = em.unwrap(Session.class);
        Connection conn = SessionFactoryUtils.getDataSource(
            session.getSessionFactory()).getConnection();
        DatabaseConnection connection = new DatabaseConnection(conn);
        ITable actualTable = connection.createTable("MY_ENTITY");

        // get expected dataset
        IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass().getResource("dataset.xml"));
        ITable expectedTable = expectedDataSet.getTable("MY_ENTITY");

        // compare the dataset
        Assertion.assertEquals(expectedTable, actualTable);
    }
}

Problem

This code never ends, it seems to freeze (infinite loop ?) during this command:

ITable actualTable = connection.createTable("MY_ENTITY");

But if I comment the em.flush() block, the test ends (no freeze or infinite loop). In this case, the test fails because the database has not been updated after the insert.


Question

how can I test the create method of a DAO using a similar approach (compare dataset with dbunit) without having a freeze when calling dataset.getTable() ?

Was it helpful?

Solution

I found the solution. The problem was caused by the connection.

If I replace :

Session session = em.unwrap(Session.class);
Connection conn = SessionFactoryUtils.getDataSource(
        session.getSessionFactory()).getConnection();

by

DataSource ds = (DataSource) applicationContext.getBean("dataSource");
Connection conn = DataSourceUtils.getConnection(ds);

All runs fine...

I don't understand why, so let me know in comments if you have any clue to help me understand that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top