java 如何执行测试以检查执行器指标是否存在?404 for /actuator/prometheus

uinbv5nw  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(221)

我有一个Sping Boot 应用程序(版本是3.0.4):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.4</version>
    <relativePath/>
</parent>

在应用程序application.yamlsrc/main/resources)中,我有以下配置:

....
    management:
      server:
        port: 8081
      endpoints:
        web:
          exposure:
            include: health,prometheus,info
      endpoint:
        info:
          enabled: true
        health:
          enabled: true
          probes:
            enabled: true
          show-details: always
        prometheus:
          enabled: true
      ...

当我在浏览器中运行应用程序并访问url localhost:8081/actuator/prometheus时,我看到一长串指标,这是预期的
现在我想实现测试,以确保prometheus指标可用:

@Slf4j
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class ActuatorTests {
    @Autowired
    protected TestRestTemplate testRestTemplate;

    @LocalManagementPort
    private int managementPort;

    @Test
    public void test1() {
        ResponseEntity<String> forEntity = testRestTemplate.getForEntity("/actuator/prometheus", String.class);
        assertEquals(HttpStatus.OK, forEntity.getStatusCode());

    }

    @Test
    public void test2() {
        ResponseEntity<String> actuatorResponse = testRestTemplate.getForEntity("http://localhost:" + managementPort + "/actuator/prometheus", String.class);
        assertEquals(HttpStatus.OK, actuatorResponse.getStatusCode());
    }
}

两个测试均失败,出现相同错误:

org.opentest4j.AssertionFailedError: 
Expected :200 OK
Actual   :404 NOT_FOUND

我该怎么解决?
P.S.
我也试着复制这个测试:https://stackoverflow.com/a/75334796/2674303
但结果是:

org.springframework.web.client.HttpClientErrorException$NotFound: 404 : "{"timestamp":"2023-05-31T22:09:49.535+00:00","status":404,"error":"Not Found","path":"/actuator/metrics"}"
tv6aics1

tv6aics11#

测试配置中的此配置修复了以下问题:

management:
  prometheus:
    metrics.export.enabled: true

这个选项在applicaton中是不需要的(因为默认值是true)。

package org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus;
...
@ConfigurationProperties(prefix = "management.prometheus.metrics.export")
public class PrometheusProperties {

    /**
     * Whether exporting of metrics to this backend is enabled.
     */
    private boolean enabled = true;     
    ...

我没能找到一个地方,但看起来像一些Spring Boot 测试启动覆盖这个默认值。不确定这个测试是否有一个值,以防我需要更改配置使其工作。

相关问题