Spring unit test case does not roll back record insert

The following test cases function correctly functionally, but one of the testing methods associated with creating a new article in the database is not rollback at the end of the test case.
I expect this to work. For a test case that updates the article, it actually rolls back the update at the end of the test case.

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "/applicationContext-test.xml") @TransactionConfiguration(transactionManager = "txManager", defaultRollback = true) @Transactional public class PriceRepositoryTest { @Resource(name ="repository") private PriceRepository repository; @Test public void testGetAll() throws Exception { Assert.assertEquals(8, repository.getAll().size()); } @Test @Rollback public void shouldSaveNewArticle(){ Article article = new Article(); article.setName("Article"); article.setPrice(33); repository.save(article); Assert.assertEquals(9, repository.getAll().size()); } @Test @Rollback public void shouldUpdateArticle(){ Article article = repository.getArticle(4); article.setPrice(33); repository.update(article); Assert.assertEquals(String.valueOf(33.0), String.valueOf(repository.getArticle(4).getPrice())); } 

}

+7
source share
3 answers

Perhaps your DAO is also tagged @Transactional ? If so, then the problem is: the transactional ability at another level does not know about your local transaction configuration. If repository.update(article) is @Transactional , it may or may not start a new transaction (depending on the value of the propagation attribute), but it will complete the transaction after execution, and there is nothing your test method can do to intercept that.

This is one of the reasons why transactions should be started at the service level, and not at the DAO level.

(If it is not, I humbly apologize)

+5
source

I also ran into this problem and spent several hours trying to find the root cause. The problem was a variant of the problems described here. In my case, the application calls stored procedures through Spring, and one of these procedures contained a COMMIT statement.

Obligations should always be controlled by the application, if there is an invalid commit in the stored procedure, Spring cannot control the transaction, and the tests will not be rolled back.

+1
source

I just came across this when my unit tests were set to rollback, and my record still showed up in the database after the test completed. The reason was that in the DAO, the call to the entitymanager method for flush () was in the method that caused the transaction to commit transactions.

em.persist (jpaServer); em.flush (); // writes the record no matter what spring is configured to run

I took a flash and did not confirm any record. I tested the same code using a test annotated on @Rollback (false) and confirmed the record (confirmation that the flash is not needed)

  • Ben www.nimbits.com
0
source

All Articles