【问题标题】:MockMvc Integration Test with List of Object as Request Param使用对象列表作为请求参数的 MockMvc 集成测试
【发布时间】:2019-10-22 14:07:49
【问题描述】:

我正在使用 Spring MVC 开发 REST 服务,该服务将对象列表作为请求参数。

    @RequestMapping(value="/test", method=RequestMethod.PUT)
    public String updateActiveStatus(ArrayList<Test> testList, BindingResult result) throws Exception {
        if(testList.isEmpty()) {
            throw new BadRequestException();
        }
        return null;
    }

当我尝试对上述服务进行集成测试时,我无法在请求参数中发送测试对象列表。

以下代码对我不起作用。

List<Test> testList = Arrays.asList(new Test(), new Test());
        mockMvc.perform(put(ApplicationConstants.UPDATE_ACTIVE_STATUS)
                .content(objectMapper.writeValueAsString(testList)))
            .andDo(print());

谁能帮忙解决这个问题!

【问题讨论】:

    标签: spring-mvc integration-testing spring-test mockmvc spring-test-mvc


    【解决方案1】:

    @RequestParam 与列表或数组

    @RequestMapping("/books")
    public String books(@RequestParam List<String> authors,
                             Model model){
        model.addAttribute("authors", authors);
        return "books.jsp";
    }
    
    @Test
    public void whenMultipleParameters_thenList() throws Exception {
        this.mockMvc.perform(get("/books")
                .param("authors", "martin")
                .param("authors", "tolkien")
        )
                .andExpect(status().isOk())
                .andExpect(model().attribute("authors", contains("martin","tolkien")));
    }
    

    【讨论】:

      【解决方案2】:

      使用 Gson 库将列表转换为 json 字符串,然后将该字符串放入内容中

      同样将@RequestBody注解和方法参数放在控制器中

      public String updateActiveStatus(@RequestBody ArrayList&lt;...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-10
        • 2017-10-28
        • 2014-02-06
        • 2015-01-01
        • 1970-01-01
        • 2013-09-02
        • 1970-01-01
        • 2016-12-09
        相关资源
        最近更新 更多