JUnit: Setting Transaction boundry for Test Class

2019-06-01 17:51发布

问题:

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
   }


}

回答1:

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.



回答2:

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.



回答3:

Use the annotation @Before for methods that have to run before every testmethod and @After to run after every testmethod.

You can take this article as a reference.