Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring unit test case is not rolling back insertion of a record

The following test cases are functionally working properly, but one of the test methods having to create a new article in the database doesn't rollback at the end of the test case execution.
I expect it to work that way. For a test case that update article actually rollbacks the update at the end of test case execution.

@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()));
}

}

like image 507
Antony Avatar asked Feb 14 '11 06:02

Antony


1 Answers

Is your DAO perhaps also marked with @Transactional? If it is, that's the problem: the transactionality on a different layer doesn't 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 commit the transaction after execution, and there's nothing your test method can do to intercept that.

That's one of the reasons why transactions should be started on the service level, not the DAO level.

(If that's not the case, I humbly apologize)

like image 83
Sean Patrick Floyd Avatar answered Nov 24 '22 07:11

Sean Patrick Floyd