在不启动完整应用程序的情况下测试 Spring Boot Actuator 端点 问题 1问题 2

问题描述

我的 Spring Boot 应用程序配置了数据源并公开了 Spring Actuator 运行状况和 prometheus 指标。

application.yml

spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    username: ${db.username}
    password: ${db.password}
    url: jdbc:mariadb://${db.host}:${db.port}/${db.schema}

management:
  endpoints:
    web:
      exposure:
        include: 'health,prometheus'

启动应用程序时,/actuator/prometheus 会提供包含指标的响应。现在我想为 prometheus 端点编写一个非常基本的测试 (JUnit 5)。这是目前的样子:

测试类

@SpringBoottest
@ExtendWith(SpringExtension.class)
@AutoConfiguremockmvc
public class HealthMetricsIT {

    @Autowired
    private mockmvc mockmvc;

    @Test
    public void shouldProvideHealthMetric() throws Exception {
        mockmvc.perform(get("/actuator/prometheus")).andExpect(status().isOk());
    }
}

但是我在这里遇到了两个问题,我还不知道如何解决

问题 1

  • 通过这种设置,测试似乎会启动整个应用程序,从而尝试连接到正在运行的数据库
  • 测试将无法正常启动,因为未提供以 db 为前缀的数据源属性

如何在不启动数据库连接的情况下开始此测试?

问题 2

即使我的本地数据库正在运行并且我提供了所有 db 属性,测试也会失败。这次是因为我得到的是 HTTP 404 而不是 200。

解决方法

由于 MockMvc 用于测试 Spring MVC 组件(您的 @Controller@RestController),我猜您使用 @AutoConfigureMockMvc 获得的自动配置的模拟 Servlet 环境将不包含任何 Actuator 端点。

相反,您可以编写一个不使用 MockMvc 的集成测试,而是启动您的嵌入式 Servlet 容器。

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
// @ExtendWith(SpringExtension.class) can be omitted with recent Spring Boot versions
public class HealthMetricsIT {

    @Autowired
    private WebTestClient webTestClient; // or TestRestTemplate

    @Test
    public void shouldProvideHealthMetric() throws Exception {
      webTestClient
       .get()
       .uri("/actuator/health")
       .exchange()
       .expectStatus().isOk();
    }
}

对于此测试,您必须确保应用启动时所需的所有基础架构组件(数据库等)都可用。

使用测试容器,您几乎可以毫不费力地provide a database for your integration test