Question

Let's say we have the next test:

@ContextConfiguration(classes = {MyDaoContext.class})
public class MyDaoTest extends AbstractTransactionalTestNGSpringContextTests {

@Autowired
private MyDao dao;

@Test
public void insertDataTest() {
    // insert data here and test something
}

@Test(dependsOnMethods = "insertDataTest")
public void modifyPreviouslyInsertedDataTest() {
    // get previously inserted data and test something
}
}

Second test will fall because when we have finished first test the inserted data are gone. Is there a way to rollback a transaction after all tests have finished their work?

Was it helpful?

Solution

Each test runs in its own transaction and rollbacks at the end. You can tune that by adding @Rollback(false) to your first test.

The problem now is that the transaction of insertDataTest has completed so you should remove what it has created manually. To do that, the class you extends from has several utility methods such as deleteFromTables or deleteFromTableWhere.

This should go ideally in an @AfterClass or something.

But that's not what I would do. I would factor out the data that are inserted by insertDataTest in a shared utility. That way, you could call it again in your second test and remove the dependsOnMethods. Having such dependency is not recommended as you can't run that test in isolation.

OTHER TIPS

Try the following (which would work in JUnit, I'm not sure about TestBG)

@ContextConfiguration(classes = {MyDaoContext.class})
public class MyDaoTest extends AbstractTransactionalTestNGSpringContextTests {

   @Autowired
   private MyDao dao;

   @Test
   @Rollback(false)
   public void insertDataTest() {
       // insert data here and test something
   }

   @Test(dependsOnMethods = "insertDataTest")
   public void modifyPreviouslyInsertedDataTest() {
       // get previously inserted data and test something
   }
}

In that case of course you would have to delete the data from the first method manually

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top