指定端口时,Spring Boot Actuator端点的单元测试无效

WHG*_*BBO 9 junit spring-boot spring-boot-actuator

最近我改变了我的spring boot属性来定义一个管理端口.这样做,我的单元测试开始失败:​​(

我编写了一个测试/ metrics端点的单元测试,如下所示:

@RunWith (SpringRunner.class)
@DirtiesContext
@SpringBootTest
public class MetricsTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    /**
     * Called before each test.
     */
    @Before
    public void setUp() {
        this.context.getBean(MetricsEndpoint.class).setEnabled(true);
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    /**
     * Test for home page.
     *
     * @throws Exception On failure.
     */
    @Test
    public void home()
            throws Exception {
        this.mvc.perform(MockMvcRequestBuilders.get("/metrics"))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}        
Run Code Online (Sandbox Code Playgroud)

以前这是过去了.添加后:

management.port=9001
Run Code Online (Sandbox Code Playgroud)

测试开始失败:

home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>
Run Code Online (Sandbox Code Playgroud)

我尝试用以下方法更改@SpringBootTest注释:

@SpringBootTest (properties = {"management.port=<server.port>"})
Run Code Online (Sandbox Code Playgroud)

server.port使用的编号在哪里.这似乎没有任何区别.

然后将属性文件中的management.port值更改为与server.port相同.结果相同.

让测试工作的唯一方法是从属性文件中删除management.port.

有什么建议/想法吗?

谢谢

Dmy*_*nko 5

对于 Spring Boot 2.x,可以简化集成测试配置。

例如简单的自定义heartbeat端点

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

    @ReadOperation
    public String heartbeat() {
        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

此端点的集成测试

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

    }

}    
Run Code Online (Sandbox Code Playgroud)


bin*_*ary 1

尝试使用

@SpringBootTest(properties = {"management.port="})
Run Code Online (Sandbox Code Playgroud)

注释中定义的属性比应用程序属性中定义的属性@SpringBootTest具有更高的优先级。"management.port="将“取消设置”该management.port属性。
这样您就不必担心在测试中配置端口。