簡體   English   中英

帶有單元測試的 Spring Boot 測試 API 端點應該返回 404 而不是 400

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM