java JUnit:为测试类设置事务边界

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11948147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:03:17  来源:igfitidea点击:

JUnit: Setting Transaction boundry for Test Class

javaspringjunitjunit4spring-test

提问by Ashika Umanga Umagiliya

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
   }


}

回答by Tomasz Nurkiewicz

In Spring just add @Transactionalannotation over your test case class:

在 Spring 中,只需@Transactional在您的测试用例类上添加注释:

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

Check out official documentationfor very in-depth details, including @TransactionConfiguration, @BeforeTransaction, @AfterTransactionand other features.

请查看官方文档非常深入的细节,包括@TransactionConfiguration@BeforeTransaction@AfterTransaction和其他功能。

回答by JMelnik

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 启动方法,在每次测试后使用@After 启动方法。在方法或类上使用@Transactional spring 的注释来启动事务,并使用@Rollback 回滚事务中完成的所有事情。

@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.

也有以另一种方式解决的相同问题

回答by oopbase

Use the annotation @Beforefor methods that have to run before every testmethod and @Afterto run after every testmethod.

@Before对必须在每个测试方法之前运行和在每个测试方法之后运行的方法使用注释@After

You can take this articleas a reference.

你可以把这篇文章作为参考。