Gourav
Gourav

Reputation: 813

MockMvc Integration Test with List of Object as Request Param

I am working on a REST service using Spring MVC which takes List of Object as request parameter.

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

When I am trying a Integration test for above service, I am not able to send the list of Test object in request param.

Following code is not working for me.

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

Can anyone please help on this!

Upvotes: 2

Views: 11666

Answers (3)

Yassine CHABLI
Yassine CHABLI

Reputation: 3734

In case of using the parameter as List by the RequestParams:

In my case, it was a list on Enum values.

when(portService.searchPort(Collections.singletonList(TypeEnum.NETWORK))
                .thenReturn(searchDto);


ResultActions ra = mockMvc.perform(get("/port/search")
        .param("type", new String[]{TypeEnum.NETWORK.name()}));

Upvotes: 1

user10988894
user10988894

Reputation:

@RequestParam with List or array

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

Upvotes: 3

muasif80
muasif80

Reputation: 6006

Use Gson library to convert list into a json string and then put that string in content

Also put the @RequestBody annotation with the method parameter in the controller

public String updateActiveStatus(@RequestBody ArrayList<...

Upvotes: 1

Related Questions