【问题标题】:Spring Boot test API endpoint with unit testing should return 404 instead of 400带有单元测试的 Spring Boot 测试 API 端点应该返回 404 而不是 400
【发布时间】: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


    【解决方案1】:
    "/experts/999", 42L
    

    这不是 objectId。

    试试类似的东西

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 您能解释一下 42L 是如何转换为 ObjectId 的吗?
      • 既然你传的是 Long 类型的值,为什么不用 Long id 作为参数呢?
      • 因为我使用的是 mongo 而我的 id 只能是 ObjectId 类型
      • 试试这个,42L 用于 mongoDB 对象 id,例如“5aeccb0a18365ba07414356e”
      猜你喜欢
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2020-06-15
      • 2018-12-13
      相关资源
      最近更新 更多