Spring boot 在弹簧靴的H2中加载初始测试数据

Spring boot 在弹簧靴的H2中加载初始测试数据,spring-boot,Spring Boot,我正在使用SpringBoot1.5.8.0版本,并使用H2内存数据库编写测试用例。目前在每个测试用例类中,我们都有@Before注释,在这里我们使用Spring数据类插入数据 我想知道,我能不能在项目中有一个地方,在那里我们可以为我们所有的测试用例定义数据。数据库表由Hybernate使用实体类创建。唯一需要的是在每个测试用例类中从单个位置插入数据,而不是从@Before插入数据 我尝试使用包含Insert语句的data.sql,但使用它时,Spring不会生成模式对象(表),因此我会出现ge

我正在使用SpringBoot1.5.8.0版本,并使用H2内存数据库编写测试用例。目前在每个测试用例类中,我们都有@Before注释,在这里我们使用Spring数据类插入数据

我想知道,我能不能在项目中有一个地方,在那里我们可以为我们所有的测试用例定义数据。数据库表由Hybernate使用实体类创建。唯一需要的是在每个测试用例类中从单个位置插入数据,而不是从@Before插入数据

我尝试使用包含Insert语句的data.sql,但使用它时,Spring不会生成模式对象(表),因此我会出现get table not found错误。我不想为schema.sql中的每个表指定CREATETABLE语句

应用程序测试.yml

spring:
  datasource:
    url: jdbc:h2:mem:test;
    driverClassName: org.h2.Driver
    username: sa
    password: 
  jpa:
    database: h2
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create
      naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    properties: 
      hibernate:
        show_sql: true
        format_sql: false
CREATE SCHEMA AB AUTHORIZATION SA;
Schema.sql

spring:
  datasource:
    url: jdbc:h2:mem:test;
    driverClassName: org.h2.Driver
    username: sa
    password: 
  jpa:
    database: h2
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create
      naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    properties: 
      hibernate:
        show_sql: true
        format_sql: false
CREATE SCHEMA AB AUTHORIZATION SA;
AbcControllerTest.java

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
@SpringBootTest(classes = WebApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AbcControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private LeDataService leDataService;

  @Before
  public void setup() {
    MyInfo myInfo = new MyInfo();
    ..............
    ..............
    leDataService.save(myInfo);
  }

  @Test
  public void getAbcTest() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/Abcs/1234567/12345678")
        .with(SecurityMockMvcRequestPostProcessors.user("test").password("test123"))
        .with(SecurityMockMvcRequestPostProcessors.csrf()))
        .andExpect(status().isOk())
  }

}

创建带有
@Component@Profile({“dev”,“test”})
注释并实现
CommandLineRunner
的新类,然后注入依赖项

使用CommandLineRunner附带的初始数据覆盖run()方法

比如说

    @Component 
    @Profile({ "dev", "test" })
    setupInitialData implements CommandLineRunner {

    UserService userService;

    //bla bla

    @Override
    @Transactional
    public void run(String... args) {
       User user = new User;
       user.setName("test");
       userService.save(user);

       //bla bla
    }

 }
你可以看看这里:尤其是这个答案适用于你的情况: