13

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?

Laplas
  • 687
  • 1
  • 7
  • 10
Nilesh
  • 4,137
  • 6
  • 39
  • 53

3 Answers3

25

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.

nobeh
  • 9,784
  • 10
  • 49
  • 66
13

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • sorry should have added that i am using hibernate for persistence. – Nilesh May 23 '12 at 11:28
  • 2
    It wasn't supposed to be a comment on your answer anyway :-). BTW the best practice you mentioned above is well published. I think you got lost in trying to be pedantic and forgot to answer the real question! – Nilesh May 23 '12 at 11:42
  • 2
    If the best practice is so well published, why are you not following it? I have no way to conclude what you know based on what you posted. And I think I did answer the question. The fact that you didn't commit is pertinent. Others have suggested the same thing. How is that not answering the question? – duffymo May 23 '12 at 11:44
8

From the "Testing" section of the docs, you can use the

 @Rollback(false) 

annotation if you don't want SpringJUnit4ClassRunner to roll back your transactions.

stites
  • 4,903
  • 5
  • 32
  • 43
stevedbrown
  • 8,862
  • 8
  • 43
  • 58