【问题标题】:JUnit: Setting Transaction boundry for Test ClassJUnit:为测试类设置事务边界
【发布时间】:2012-08-14 08:03:29
【问题描述】:

我想在任何测试方法开始之前启动数据库事务,并在运行所有测试结束时回滚所有事务。

怎么做?我应该使用什么注释?

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


}

【问题讨论】:

    标签: java spring junit junit4 spring-test


    【解决方案1】:

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

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

    查看official documentation 了解详细信息,包括@TransactionConfiguration@BeforeTransaction@AfterTransaction 和其他功能。

    【讨论】:

    • 是的,这是最简单的方法,但通常强烈建议不要使用 @Transactional 在测试中管理事务。你甚至写过关于那个主题的文章:Spring Pitfalls: Transactional tests considered harmful :)
    • 我通常使用上面给出的方法,但@G.Demecki 是正确的,我已经被这样咬过几次了。
    【解决方案2】:

    使用@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
    }
    

    还有same issue solved in another way

    【讨论】:

      【解决方案3】:

      注释@Before 用于必须在每个测试方法之前运行的方法,@After 用于在每个测试方法之后运行。

      您可以将this article作为参考。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多