gpt4 book ai didi

java - 指定端口时,Spring Boot Actuator 端点的单元测试不起作用

转载 作者:行者123 更新时间:2023-12-04 04:29:39 25 4
gpt4 key购买 nike

最近我改变了我的 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());
}
}

以前这是通过。添加后:
management.port=9001

测试开始失败:
home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>

我尝试使用以下方法更改 @SpringBootTest 注释:
@SpringBootTest (properties = {"management.port=<server.port>"})

server.port 使用的数字在哪里。这似乎没有任何区别。

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

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

任何建议/想法?

谢谢

最佳答案

对于 Spring 启动测试,我们需要指定它需要连接的端口。

默认情况下,它连接到 server.port在执行器的情况下是不同的。

这可以通过

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

application.properties我们指定管理端口如下
...
management.port=8090
...

关于java - 指定端口时,Spring Boot Actuator 端点的单元测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com