How to re-create database before each test in Spring?

后端 未结 9 2192
盖世英雄少女心
盖世英雄少女心 2020-12-07 16:30

My Spring-Boot-Mvc-Web application has the following database configuration in application.properties file:

spring.datasource.url=jdbc:h2:tcp://         


        
9条回答
  •  北海茫月
    2020-12-07 16:52

    You can annotate your test class with @Transactional:

    import org.springframework.transaction.annotation.Transactional;
    ...
    
    ...
    @RunWith(SpringRunner.class)
    @Transactional
    public class MyClassTest {
    
        @Autowired
        private SomeRepository repository;
    
        @Before
        public void init() {
           // add some test data, that data would be rolled back, and recreated for each separate test
           repository.save(...);
        }
    
        @Test
        public void testSomething() {
           // add some more data
           repository.save(...);
           // update some base data
           repository.delete(...);
           // all the changes on database done in that test would be rolled back after test finish
        }
    }
    

    All tests are wrapped inside a transaction, that is rolled back at the end of each test. There are unfortunately some problems with that annotation of course, and you need to pay special attention, when for example your production code uses transactions with different score.

提交回复
热议问题