MockMvc集成测试,对象列表作为请求参数

时间:2019-06-07 04:34:33

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

我正在使用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;
    }

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

以下代码对我不起作用。

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

任何人都可以帮忙!

2 个答案:

答案 0 :(得分:1)

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

也将@RequestBody注释和方法参数放在控制器中

public String updateActiveStatus(@RequestBody ArrayList<...

答案 1 :(得分:0)

  

@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")));
}