Announcement Announcement Module
No announcement yet.
Spring DAO Unit Testing access to connection Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring DAO Unit Testing access to connection


    I am trying to write unit tests for my Spring enhanced Hibernate DAOs. I am using DBUnit and AbstractTransactionalDataSourceSpringContextTests.

    Now, I subscribe to the speed benefits of always rolling back unit tests (not integration - got to be able to test optimistic locking, etc). But, I am having issues coming up with a nice design to access the connection that Hibernate is using so that I can perform DBUnit assertions against my database within the same connection.

    An alternative would be to let the transaction commit and then do the DBUnit assertions in another connection but that defeats the rollback gains.

    Any thoughts would be appreciated greatly.

    <p.s.> If Hibernate and Spring were chicks, they'd both be hot. So, I hope Hibernate starts being nice to the new hot chick in town.

    Joe Witt

  • #2
    You could override the onTearDownInTransaction() method, then get the DataSource and create a DBUnit Connection wrapper like:
            DataSource ds = jdbcTemplate.getDataSource&#40;&#41;;
            Connection con = DataSourceUtils.getConnection&#40;ds&#41;;
            // create a DbUnit connection wrapper
            IDatabaseConnection dbUnitCon = new DatabaseConnection&#40;con&#41;;
    As long as the Hibernate Session usees the same DataSource your code should now run in the same transaction.


    • #3
      Thank you.

      I have also noticed I 'could' access the Hibernate session used in the current transaction via SessionFactoryUtils.getSession(SessionFactory sessionFactory, boolean allowCreate).

      That said, the solution you propose ( DataSourceUtils.getConnection(ds) ) seems much better as I don't want access a connection via a Hibernate session if I can access the connection directly.

      My only concern now is if the TransactionManager I'm using binds the connection to the thread as required for this.

      Thanks again,