在查看了 stackoverflow 等之后,我尝试了很多,但我找不到解决方案,因为我的测试无法找到我的自定义运行状况指标。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
@AutoConfigureMockMvc
@TestPropertySource(properties = { "management.server.port=0" })
class MyCassandraHealthIndicatorTest {
@Autowired
private WebTestClient webClient;
@LocalServerPort
// private String port = "10000";
private String port;
@Autowired
private WebApplicationContext context;
@MockBean
private MyCassandraHealthIndicator healthIndicator;
@MockBean
private Health.Builder builder;
@Autowired
protected MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
void checkCassandraHealthUp() {
webClient.get().uri("/actuator/health/mycassandra")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("status")
.isEqualTo("UP");
}
}
当前结果:
java.lang.AssertionError: Status expected:<200 OK> but was:<404 NOT_FOUND>
> GET http://localhost:65188/actuator/health/mycassandra
> WebTestClient-Request-Id: [1]
No content
< 404 NOT_FOUND Not Found
< Vary: [Origin, Access-Control-Request-Method, Access-Control-Request-Headers]
< Content-Type: [application/json]
< Transfer-Encoding: [chunked]
< Date: [Fri, 01 Oct 2021 11:49:23 GMT]
{"timestamp":"2021-10-01T11:49:23.387+00:00","status":404,"error":"Not Found","message":"","path":"/actuator/health/mycassandra"}
在浏览器中调用 URL 可以完美运行。