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

后端 未结 9 2194
盖世英雄少女心
盖世英雄少女心 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:54

    Using the accepted answer in Spring-Boot 2.2.0, I was seeing JDBC syntax errors related to constraints:

    Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Constraint "FKEFFD698EA2E75FXEERWBO8IUT" already exists; SQL statement: alter table foo add constraint FKeffd698ea2e75fxeerwbo8iut foreign key (bar) references bar [90045-200]

    To fix this, I added @AutoConfigureTestDatabase to my unit test (part of spring-boot-test-autoconfigure):

    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
    import org.springframework.test.annotation.DirtiesContext;
    import org.springframework.test.annotation.DirtiesContext.ClassMode;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.junit4.SpringRunner;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
    @AutoConfigureTestDatabase(replace = Replace.ANY)
    public class FooRepositoryTest { ... }
    

提交回复
热议问题