【发布时间】:2020-01-24 14:34:35
【问题描述】:
我的 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 响应?提前感谢您的回答。
【问题讨论】:
标签: java spring mongodb spring-boot unit-testing