Unit testing of Spring Boot Actuator endpoints not working when specifying a port

…衆ロ難τιáo~ 提交于 2019-12-04 02:58:09

Did you try adding the following annotation to your test class?

@TestPropertySource(properties = {"management.port=0"})

Check the following link for reference.

Had the same issue, you just have to make the management.port null by adding this in your application-test.properties (set it to empty value)

management.port=

Make sure you use the test profile in your JUnit by annotating the class with

@ActiveProfiles("test")

Isn't there an error in the property name? Shouldn't be @TestPropertySource(properties = {"management.server.port=..."}) instead of @TestPropertySource(properties = {"management.port=.."})

MirzaM

For Spring boot test we need to specify the port it needs to connect to.

By default, it connects to server.port which in case of actuators is different.

This can be done by

@SpringBootTest(properties = "server.port=8090")

in application.properties we specify the management port as below

...
management.port=8090
...

For Spring Boot 2.x the integration tests configuration could be simplified.

For example simple custom heartbeat endpoint

@Component
@Endpoint(id = "heartbeat")
public class HeartbeatEndpoint {

    @ReadOperation
    public String heartbeat() {
        return "";
    }
}

Where integration test for this endpoint

@SpringBootTest(
        classes = HeartbeatEndpointTest.Config.class,
        properties = {
                "management.endpoint.heartbeat.enabled=true",
                "management.endpoints.web.exposure.include=heartbeat"
        })
@AutoConfigureMockMvc
@EnableAutoConfiguration
class HeartbeatEndpointTest {

    private static final String ENDPOINT_PATH = "/actuator/heartbeat";

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHeartbeat() throws Exception {
        mockMvc
                .perform(get(ENDPOINT_PATH))
                .andExpect(status().isOk())
                .andExpect(content().string(""));
    }

    @Configuration
    @Import(ProcessorTestConfig.class)
    static class Config {

        @Bean
        public HeartbeatEndpoint heartbeatEndpoint() {
            return new HeartbeatEndpoint();
        }

    }

}    

Try using

@SpringBootTest(properties = {"management.port="})

Properties defined in the @SpringBootTest annotation have a higher precedence than those in application properties. "management.port=" will "unset" the management.port property.
This way you don't have to worry about configuring the port in your tests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!