java - 为什么 Spring Boot 控制器测试返回 404,但在上下文中找到控制器?
问题描述
我有一个我正在尝试测试的 REST 控制器,但是在尝试向其发布时,我得到一个 404。测试是 JUnit 5 和 Spring Boot 2.1.5。如果我运行应用程序,我可以通过 Postman 访问控制器。我已经在调试模式下运行它并验证它myController
不为空并且已将模拟服务注入其中。我在这里想念什么?spring-boot-starter-test 是一个依赖项,而 junit4 是一个排除项。
@RestController
@Slf4j
@RequestMapping(path = /integrations,
produces = "application/json")
public class MyController {
private MyService myService;
private MyValidationService myValidationService;
public MyController(MySerivce service, MyValidationService myValidationService) {
this.myService = service;
this.myValidationService = myValidationService;
}
@PostMapping(path = "/users", produces = "application/json", consumes =
"application/json")
public ResponseEntity<User> getUserList(@Valid @RequestBody final RequestPayload
requestPayload, @RequestHeader Map<String, String> headers) throws MyException {
// check the credentials and permission
Map<String, String> credInfo = myValidationService.validateHeaders(headers);
// process payload
return myService.retrieveUsers(requestPayload);
}
}
测试如下:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
class MyControllerTest {
@MockBean
private MyService myService;
@MockBean
private MyValidationService myValidationService;
@Autowired
private MockMvc mockMvc;
@Autowired
MyController myController;
@Test
public void contextLoads() throws Exception {
Assert.assertNotNull(myController);
}
@Test
void getUserList() throws Exception {
List<User> users = returnUserList();
HttpEntity<RequestPayload> requestHttpEntity = new HttpEntity<>(returnPayload(), null);
when(myService.retrieveUsers(any(RequestPayload.class))).thenReturn(users);
mockMvc.perform(post("/integrations/users")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(returnPayload()))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful());
}
}
我得到的回应是:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
解决方案
我很欣赏这些答案,但我发现了问题所在 - 这是一个愚蠢的问题!
事实证明,当application.properties文件中已经提供了该值时,我在 mockMvc 调用中包含了上下文路径!因此,使用的真正 URI 不是/integrations/users的 URI,而是/integrations/integrations/users,这并不奇怪!
感谢所有人,很抱歉没有把我的眼睛放在我的手中并仔细观察。
推荐阅读
- android-layout - 如何使选项卡仅对导航抽屉项目之一可见?
- sql - 我想修剪 SQL 中的名称。例如。我的数据有一个名称为美国航空公司,与“美国航空公司”相同
- javascript - javascript 不适用于 Bootstrap/rails 应用程序
- git - GitLab CE 版问题(创建随机贡献者)
- angular - Angular Material 单选按钮行为不正常
- visual-studio - Vue.js HTML 模板编译时检查
- c# - 无法原始打印到 RDP 重定向打印机
- angular - Lazy loading feature module not working
- apostrophe-cms - 布局小部件错误:“您无法控制文档”
- ruby-on-rails - 离子日期时间字段、Rails API 和时区