JUnit: Setting Transaction boundry for Test Class

2019-06-01 17:57发布

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
   }


}

3条回答
Animai°情兽
2楼-- · 2019-06-01 18:31

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.

查看更多
放我归山
3楼-- · 2019-06-01 18:33

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.

查看更多
Root(大扎)
4楼-- · 2019-06-01 18:34

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.

查看更多
登录 后发表回答