spring引导测试api端点应该返回404而不是400

7bsow1i6  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(320)

我的spring引导应用程序上有以下控制器,它连接到 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响应?提前谢谢你的回答。

bn31dyow

bn31dyow1#

对于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值。

czfnxgou

czfnxgou2#

"/experts/999", 42L

这不是objectid。
试试这样的

mockMvc.perform(MockMvcRequestBuilders.get("/experts/58d1c36efb0cac4e15afd278")
 .contentType(MediaType.APPLICATION_JSON)
 .accept(MediaType.APPLICATION_JSON))
 .andExpect(MockMvcResultMatchers.status().isNotFound());

相关问题