JUnit: setting transaction boundaries for test class

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

How to do it? 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
   }


}

      

+1


source to share


3 answers


Use @Before to run a method before any test and @After run a method after each test. Use @Transactional spring annotation on a method or above a class to start a transaction, and @Rollback is to rollback everything done in a 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
}

      



There is also the same question, solved in a different way .

+3


source


In Spring, just add annotation @Transactional

to your test case class:

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

      



Check out the official documentation for more More, including @TransactionConfiguration

, @BeforeTransaction

, @AfterTransaction

and other functions.

+4


source


Use annotation @Before

for methods to be executed before each test method and @After

to run after each test method.

You can take this article as a reference.

+1


source







All Articles