指定端口时,Spring Boot Actuator端点的单元测试不起作用 [英] Unit testing of Spring Boot Actuator endpoints not working when specifying a port

查看:321
本文介绍了指定端口时,Spring Boot Actuator端点的单元测试不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我更改了spring boot属性以定义管理端口. 这样,我的单元测试开始失败:(

recently I changed my spring boot properties to define a management port. In doing so, my unit tests started to fail :(

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

I wrote a unit test that tested the /metrics endpoint as follows:

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

以前,这已经过去了.添加后:

Previously this was passing. After adding:

management.port=9001

测试开始失败,并显示以下信息:

The tests started failing with:

home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>

我尝试通过以下方式更改@SpringBootTest批注:

I tried changing the @SpringBootTest annotation with:

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

其中是用于server.port的编号.这似乎没有什么区别.

Where is the number used for the server.port. This didn't seem to make any difference.

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

So then changed the management.port value in the property file to be the same as the server.port. Same result.

使测试生效的唯一方法是从属性文件中删除management.port.

The only way to get the test to work is remove the management.port from the property file.

有什么建议/想法吗?

谢谢

推荐答案

您是否尝试将以下注释添加到测试类?

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

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

查看以下链接以供参考.

这篇关于指定端口时,Spring Boot Actuator端点的单元测试不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆