【问题标题】:Transaction roll back is not working in test case in @Nested class of JUnit5事务回滚在 JUnit5 的 @Nested 类的测试用例中不起作用
【发布时间】:2017-10-27 10:42:32
【问题描述】:

我用的是spring-boot、JUnit5、Mybatis。

@SpringJUnitJupiterConfig(classes = {RepositoryTestConfig.class})
@MapperScan
@Rollback
@Transactional
public class TestClass {
    @Autowired
    private TestMapper testMapper;

    @BeforeEach
    void init() {
        User user = new User();
        testMapper.insert(user);    
    }

    @Test
    public void test1() {
        // (1) success rollback
    }

    @Nested
    class WhenExistData {
        @Test
        public void test2() {
            // (2) rollback not working
        }   
    }
}

(1) 正在回滚。并输出以下日志。

2017-05-26 22:21:29 [INFO ](TransactionContext.java:136) Rolled back transaction for test context ...

但是,(2) 不起作用。我希望能够回滚到@Nested

【问题讨论】:

    标签: java spring spring-boot mybatis junit5


    【解决方案1】:

    这是意料之中的:Spring TestContext 框架从未支持嵌套测试类的“继承”。

    因此,您的“变通”实际上是此时实现目标的正确方法。

    但是请注意,我可能会结合SPR-15366嵌套 测试类添加对“伪继承”的支持。

    问候,

    Sam(Spring TestContext 框架的作者

    【讨论】:

      【解决方案2】:

      我通过以下方式解决了..

      @SpringJUnitJupiterConfig(classes = {RepositoryTestConfig.class})
      @MapperScan
      @Rollback
      @Transactional
      public class TestClass {
          @Autowired
          private TestMapper testMapper;
      
          @BeforeEach
          void init() {
              User user = new User();
              testMapper.insert(user);    
          }
      
          @Nested
          @SpringJUnitJupiterConfig(classes = {RepositoryTestConfig.class})
          @MapperScan
          @Rollback
          @Transactional
          class WhenExistData {
              @Test
              public void test2() {
              }   
          }
      }
      

      【讨论】:

      • 哦,该死的我忘了编辑我的评论。啊!我不小心链接到了错误的项目,this one 可能会更好。但我们会看到...
      • JUnit 5 和我个人的 spring-test-junit5 存储库都不适合提出此类问题。正确的地方是 Spring 的 JIRA 问题跟踪器。 ;-)
      【解决方案3】:

      我是通过以下方式解决的

      import org.junit.jupiter.api.Assertions;
      import org.junit.jupiter.api.Test;
      import org.springframework.test.annotation.Rollback;
      import org.springframework.transaction.annotation.Transactional;
      
      // JUnit5
      @SpringBootTest
      public class TestClass {
      
          @Resource
          private TestMapper testMapper;
      
          @Test
          @Rollback
          @Transactional
          public void createByTimerId() {
              Assertions.assertEquals(1, testMapper.insert());
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多