【问题标题】:Testing Spring Boot Actuator endpoint without starting full application在不启动完整应用程序的情况下测试 Spring Boot Actuator 端点
【发布时间】:2021-04-30 09:14:13
【问题描述】:

我的 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。

【问题讨论】:

    标签: spring spring-boot spring-boot-test


    【解决方案1】:

    由于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();
        }
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2018-09-07
      相关资源
      最近更新 更多