How do I reset my database state after each unit test without making the whole test a transaction?

前端 未结 6 1832
心在旅途
心在旅途 2020-12-16 09:50

I\'m using Spring 3.1.1.RELEASE, Hibernate 4.1.0.Final, JPA 2, JUnit 4.8.1, and HSQL 2.2.7. I want to run some JUnit tests on my service methods, and after each test, I wou

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 10:18

    If you use flyway for migrations, I use the following pattern:

    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class JUnit5Class {
        @Autowired
        Flyway flyway;
    
        @BeforeAll
        public void cleanUp(){
            flyway.clean();
            flyway.migrate();
        }
    }
    

    @TestInstance allows you to make @BeforeAll non static and thus you can migrate only once per test class. If you want to reset it for each test remove the class anotation and make change @BeforeAll to @BeforeEach.

提交回复
热议问题