当 prometheus 端点调用时 MockMvc 收到 404

Mat*_*W90 5 java spring-boot prometheus

我想使用MockMvc类测试 Prometheus 指标端点。

一切正常,但昨天我将项目迁移到Java 15,SpringBoot 2.4.3和SpringCloud 2020.0.1. 现在,只有普罗米修斯测试不起作用,我收到404而不是预期的200。我对build.gradleeq:有所有必要的依赖runtime("io.micrometer:micrometer-registry-prometheus")。在application-test.yml我有一个禁用安全配置,合同测试协议代理端点等。

我的测试:

@ExtendWith({SpringExtension.class, PostgresSpringDataSourceExtension.class})
@ActiveProfiles({"test"})
@SpringBootTest
@AutoConfigureMockMvc
public class PrometheusEndpointTest {

 @Autowired private MockMvc mockMvc;

 @Test
 public void metricsThroughPrometheusEndpoint() throws Exception {
  MvcResult result = 
  this.mockMvc.perform(get("/metrics")).andExpect(status().isOk()).andReturn();
 }
}
Run Code Online (Sandbox Code Playgroud)

部分application.yaml配置:

management:
  endpoint:
    prometheus:
      enabled: true
  endpoints:
    enabled-by-default: false
    web:
      exposure:
        include: 'prometheus'
      base-path: '/'
      path-mapping:
        prometheus: 'metrics'
Run Code Online (Sandbox Code Playgroud)

Mat*_*W90 6

解决方案:我们需要将属性添加到测试注释或application-test.yml:

@ExtendWith(SpringExtension.class)
@SpringBootTest(
  webEnvironment = RANDOM_PORT,
  properties = "management.metrics.export.prometheus.enabled")
@ActiveProfiles({"test"})
@AutoConfigureMockMvc
Run Code Online (Sandbox Code Playgroud)