普罗米修斯端点调用时 MockMvc 收到 404

MockMvc receive 404 when prometheus endpoint is calling

我想使用 MockMvc class.

测试 Prometheus 指标端点

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

我的测试:

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

部分application.yaml配置:

management:
  endpoint:
    prometheus:
      enabled: true
  endpoints:
    enabled-by-default: false
    web:
      exposure:
        include: 'prometheus'
      base-path: '/'
      path-mapping:
        prometheus: 'metrics'

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

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