【问题标题】:Loading initial test data in H2 in spring boot在 Spring Boot 中加载 H2 中的初始测试数据
【发布时间】:2018-04-16 05:28:27
【问题描述】:

我正在使用 Spring Boot 1.5.8.Release 并在内存数据库中使用 H2 编写测试用例。目前在每个测试用例类中,我们都有 @Before 注解,我们使用 Spring Data 类插入数据。

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

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

application-test.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

Schema.sql

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

}

【问题讨论】:

标签: spring-boot


【解决方案1】:

创建带有@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
    }

 }

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2016-10-28
    • 2021-10-06
    • 2018-09-05
    • 2021-08-25
    • 2017-06-10
    • 2019-04-21
    • 2020-05-30
    • 2016-11-10
    相关资源
    最近更新 更多