首页 > 解决方案 > 在不启动完整应用程序的情况下测试 Spring Boot Actuator 端点

问题描述

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

应用程序.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());
    }
}

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

第一期

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

第 2 期

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

标签: springspring-bootspring-boot-test

解决方案


至于MockMvc测试 Spring MVC 组件(你的@Controller@RestController),我猜你得到的自动配置的模拟 Servlet 环境@AutoConfigureMockMvc不会包含任何 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();
    }
}

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

使用 Testcontainers,您几乎可以毫不费力地为集成测试提供数据库。


推荐阅读