[英]Spring Test returning 404 instead of 200 in testing Rest API in Spring Boot
[英]Spring Boot test API endpoint with unit testing should return 404 instead of 400
我的 Spring Boot 应用程序上有以下控制器,它连接到MongoDB
:
@RestController
@RequestMapping("/experts")
class ExpertController {
@Autowired
private ExpertRepository repository;
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Experts> getAllExperts() {
return repository.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Experts getExpertById(@PathVariable("id") ObjectId id) {
return repository.findBy_id(id);
}
我正在尝试在我的测试中测试get/id
端点,我希望它返回 404 响应,如下所示:
@Test
public void getEmployeeReturn404() throws Exception {
ObjectId id = new ObjectId();
mockMvc.perform(MockMvcRequestBuilders.get("/experts/999", 42L)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isNotFound());
}
尽管如此,返回的响应是 400,这意味着我的请求格式错误。 我想问题出在我在 URI 上输入的 id 上? 我知道 mongo 接受hexStrings
作为主键,所以我的问题是,我如何在我的数据库中不存在的 URI 上使用 id,以便我可以获得 404 响应? 预先感谢您的回答。
"/experts/999", 42L
这不是 objectId。
尝试类似的东西
mockMvc.perform(MockMvcRequestBuilders.get("/experts/58d1c36efb0cac4e15afd278")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isNotFound());
对于 urlVariables,您需要:
@Test
public void getEmployeeReturn404() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/experts/{id}", 42L)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isNotFound());
}
其中 42L 是您的{id} PathVariable 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.