Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: Setting Transaction boundry for Test Class

I want to start the database transactions before start of any test method and rollback all transactions at the end of running all tests.

How to do thing?What annotations should I use ?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/testApplicationContext.xml"})
public class MyTests{

   public void setUp(){
    //Insert temporary data to Database
   }

   @Test
   public void testOne(){
     //Do some DB transactions
   }

   @Test void testTwo(){
     //Do some more DB transactions
   }

   public void tearDown(){
   //Need to rollback all transactions
   }


}
like image 367
Ashika Umanga Umagiliya Avatar asked Nov 01 '25 02:11

Ashika Umanga Umagiliya


2 Answers

In Spring just add @Transactional annotation over your test case class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/testApplicationContext.xml"})
@Transactional   //CRUCIAL!
public class MyTests{

Check out official documentation for very in-depth details, including @TransactionConfiguration, @BeforeTransaction, @AfterTransaction and other features.

like image 58
Tomasz Nurkiewicz Avatar answered Nov 03 '25 17:11

Tomasz Nurkiewicz


Use @Before to launch method before any test and @After to launch method after every test. Use @Transactional spring's annotation over a method or over a class to start transaction and @Rollback to rollback everything done in transaction.

@Before   
public void setUp(){
    //set up, before every test method
}

@Transactional
@Test
public void test(){
}

@Rollback
@After
public void tearDown(){
   //tear down after every test method
}

Also there is same issue solved in another way.

like image 26
JMelnik Avatar answered Nov 03 '25 15:11

JMelnik