【问题标题】:Test database down with Spring使用 Spring 测试数据库
【发布时间】:2018-08-13 12:06:33
【问题描述】:

我需要在数据库(连接,关闭数据库..)错误期间对应用程序行为进行 Spring 测试。 有没有办法从 Spring 单元测试中关闭/杀死或启动 H2 内存数据库?

【问题讨论】:

    标签: java spring testing spring-data


    【解决方案1】:

    如果测试数据库连接,这里是旧的,但仍然很好blog on the topic。您也应该能够使用 TestContainers,以便更简单地创建数据库。

    如果您只需要在某些确切操作上测试一些失败(例如在存储库保存时),您可以简单地模拟存储库以进行测试运行:

    var mockedBean = Mockito.mock(MyRepository.class);
    var originalBean = ReflectionTestUtils.getField(articleService, fieldName);
    Mockito.when(mockedBean.save(Mockito.any(MyEntity.class))).thenThrow(new RuntimeException("My test exception"));
    ReflectionTestUtils.setField(myService, fieldName, mockedBean);
    ...
    // test here
    ...
    // set bean back for other test cases
    ReflectionTestUtils.setField(myService, fieldName, originalBean);
    

    【讨论】:

      【解决方案2】:

      使用 h2 测试数据库运行 Junit 测试时,数据库实例将在测试套件开始运行时启动,并在测试完成时停止(假设您已使用 bean 配置数据库)。

      如果您使用的是 spring-boot,那么您可以像这样配置您的 h2 测试数据库:

      src/test/resources/application-test.yml:

      spring:
        datasource:
          driverClassName: org.h2.Driver
          url: jdbc:h2:mem:testdb
          username: sa
          password:
      

      然后像这样配置你的测试:

      @RunWith(SpringRunner.class)
      @SpringBootTest
      @ActiveProfiles(profiles = "test")
      public class SignupControllerTest {
          @Autowired
          private WebApplicationContext webApplicationContext;
      
          private MockMvc mockMvc;
      
          @Autowired
          private RealityKeeperRepository myrepo;
      

      如果您使用的是常规 spring,那么您可以使用 @Profile("test") 注释配置 DataSource bean:

      @Bean
      @Profile("test")
      public DataSource devDataSource() {
          return new EmbeddedDatabaseBuilder()
              .setType(EmbeddedDatabaseType.HSQL)
              .build();
      }
      

      并像这样配置您的测试:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(classes = {AppConfig.class})
      @ActiveProfiles(profiles = "test")
      public class MyTest {
          @Autowired
          ...
      

      您的 AppConfig 类应使用 @Configuration 注释,包含上面提到的 devDataSource bean。

      【讨论】:

        【解决方案3】:

        是的,如果您有 H2 依赖项并且没有对其进行设置,那么 Spring boot 将为您启动嵌入式 H2 DB。

        这篇文章应该有用:http://www.springboottutorial.com/spring-boot-and-h2-in-memory-database

        【讨论】:

        • 谢谢,但在本文中我没有找到如何从运行单元测试中停止和启动数据库。
        • Spring 会自动为你做这件事
        • OP 询问的是如何测试数据库故障,而不是如何启动数据库。
        猜你喜欢
        • 1970-01-01
        • 2020-10-13
        • 2010-11-07
        • 1970-01-01
        • 2013-11-05
        • 2019-03-22
        • 2020-07-10
        • 2015-03-21
        • 2019-04-18
        相关资源
        最近更新 更多