Java 带有单元测试的Spring Boot测试API端点应该返回404而不是400
我的Spring Boot应用程序上有以下控制器,它连接到Java 带有单元测试的Spring Boot测试API端点应该返回404而不是400,java,spring,mongodb,spring-boot,unit-testing,Java,Spring,Mongodb,Spring Boot,Unit Testing,我的Spring Boot应用程序上有以下控制器,它连接到MongoDB: @RestController @RequestMapping("/experts") class ExpertController { @Autowired private ExpertRepository repository; @RequestMapping(value = "/", method = RequestMethod.GET) public List<Expe
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);
}
尽管如此,返回的响应是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());
对于URL变量,您需要:
@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}路径变量值。您能解释一下42L是如何转换为ObjectId的吗?既然您传递了一个长类型值,为什么不使用长id作为参数呢?因为我使用的是mongo,我的id只能是Objectedtry类型,42L表示mongoDB对象id,如“5AECCB0A18365BA0741356E”
@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());
}