Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional does not work in JUnit test?

I am using Spring 3.2, Hibernate and JUnit 4.

My Dao class is as follows:

@Transactional public class SomeDaoImpl implements SomeDao {

The update operations on this work if executed directly from web application. However, I am seeing that junit integration tests that exercise the update methods do not actually persist the changes. Is something rolling the transactions back when junit methods are executed?

like image 741
Nilesh Avatar asked May 23 '12 11:05

Nilesh


2 Answers

By reference, transactions are not persisted in test contexts in Spring. As mentioned, although unusual, if you still need to do so you can use @TransactionConfiguration and @Rollback to change the default behavior.

like image 84
nobeh Avatar answered Oct 07 '22 15:10

nobeh


DAOs should not be transactional. How can a DAO know if it should participate in a larger transaction?

Services ought to own transactions in the typical Spring layered architecture.

It's typical to run your unit tests for databases in such a way that they do roll back. You don't want your tests to alter the database, unless you've set up a test database that you can drop and recreate at will.

The question ought to be: How do your tests, as written, commit the transaction? If you never commit, you'll never see the records.

like image 42
duffymo Avatar answered Oct 07 '22 13:10

duffymo