java - Spring Boot MockMvc 测试在使用“management.server.port”属性而不是已弃用的“management.port”时为执行器端点提供 404
问题描述
我之前在应用程序 yaml 中使用 management.port 作为管理端点端口。但是,将其更改为在以下应用程序 yaml 文件中使用。它一直未能通过我对健康端点的执行器测试。当我运行应用程序时,端点正常工作。
应用程序.yaml
spring:
profiles.active: development
management:
endpoints:
web:
exposure:
include: "*"
server:
port: 9000
server:
port: 8000
---
spring:
profiles: development
logging:
level:
root: INFO
org.springframework.web: INFO
---
spring:
profiles: staging
logging:
level:
root: ERROR
org.springframework.web: ERROR
集成测试类
package com.rps;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.rps.infrastructure.repository.PlayersInMemoryRepository;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* Integration testing the actual API Check the guide here: https://spring.io/guides/gs/testing-web/
*/
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class RPSApplicationIT {
@Autowired
private WebApplicationContext context;
@Autowired
private PlayersInMemoryRepository playersInMemoryRepository;
private MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void shouldReturnActuatorHealthResponse() throws Exception {
this.mockMvc.perform(get("/actuator/health"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"status\":\"UP\"}"));
}
}
解决方案
我认为问题是由于应用程序和执行器的不同端口而出现的。
将其更改为 0 应该可以解决您的测试问题:
@TestPropertySource(properties = { "management.server.port=0" })
编辑- 我找到了一个相关的帖子,也许你可以查看那里提出的其他解决方案(即使没有接受的答案):指定端口时 Spring Boot Actuator 端点的单元测试不起作用
推荐阅读
- python - 逐块读取大文件并将其附加到python字典中
- java - 如何使用 Opencv 检测具有不同对比度和背景颜色的图像边缘?
- sql - 我想计算 DB2 游标中的行数
- mikrotik - 如何通过我的静态 IP 地址从外部网络访问 RouterOs(web 或 Winbox)
- java - Spring mvc 的问题:注释驱动
- python - 为 Linux 上的所有用户/所有代码启用 python 登录
- batch-file - xcopy 在批处理文件中使用时不起作用
- python - 如何仅在满足条件时压缩 2 个列表中的项目 - python
- visual-studio-code - vscode.workspace.openTextDocument 静默失败
- apache-kafka - 转到下一个偏移位置 kakfa