Search code examples
javaspringspring-bootmybatisjunit5

Transaction roll back is not working in test case in @Nested class of JUnit5


I use 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) is working rollback. And the following log is output.

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

But, (2) is not working. I want to be able to roll back into @Nested.


Solution

  • I solved it in the following way..

    @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() {
            }   
        }
    }