[英]Spring Boot test API endpoint with unit testing should return 404 instead of 400
I have the following controller on my Spring Boot application, which is connected to a MongoDB
:我的 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);
}
I am trying to test the the get/id
endpoint on my test, which I expect to give back an 404 response as shown below:我正在尝试在我的测试中测试
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());
}
Despite that, the response that comes back is 400, which means that my request is malformed.尽管如此,返回的响应是 400,这意味着我的请求格式错误。 I guess the problem lies on the id, which I am inputting on the URI?
我想问题出在我在 URI 上输入的 id 上? I know that mongo accepts
hexStrings
as primary keys so my question is, how could I use an id on the URI which doesnt exist on my DB so that I can get a 404 response back?我知道 mongo 接受
hexStrings
作为主键,所以我的问题是,我如何在我的数据库中不存在的 URI 上使用 id,以便我可以获得 404 响应? Thanks in advance for your answer.预先感谢您的回答。
"/experts/999", 42L
This is not an objectId.这不是 objectId。
Try something like尝试类似的东西
mockMvc.perform(MockMvcRequestBuilders.get("/experts/58d1c36efb0cac4e15afd278")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isNotFound());
For urlVariables, you need:对于 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());
}
Where 42L is your {id} PathVariable value.其中 42L 是您的{id} PathVariable 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.