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

前端之家收集整理的这篇文章主要介绍了junit – 指定端口时Spring Boot Actuator端点的单元测试无效前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近我改变了我的 spring boot属性来定义一个管理端口.
这样做,我的单元测试开始失败:​​(

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

  1. @RunWith (SpringRunner.class)
  2. @DirtiesContext
  3. @SpringBootTest
  4. public class MetricsTest {
  5.  
  6. @Autowired
  7. private WebApplicationContext context;
  8.  
  9. private MockMvc mvc;
  10.  
  11. /**
  12. * Called before each test.
  13. */
  14. @Before
  15. public void setUp() {
  16. this.context.getBean(MetricsEndpoint.class).setEnabled(true);
  17. this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
  18. }
  19.  
  20. /**
  21. * Test for home page.
  22. *
  23. * @throws Exception On failure.
  24. */
  25. @Test
  26. public void home()
  27. throws Exception {
  28. this.mvc.perform(MockMvcRequestBuilders.get("/metrics"))
  29. .andExpect(MockMvcResultMatchers.status().isOk());
  30. }
  31. }

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

  1. management.port=9001

测试开始失败:

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

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

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

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

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

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

有什么建议/想法吗?

谢谢

解决方法

您是否尝试将以下注释添加到测试类中?
  1. @TestPropertySource(properties = {"management.port=0"})

Check the following link for reference.

猜你在找的Java相关文章