2

I am using MockHttpServletRequestBuilder to create my request for testing my framework. One of the request parameters I have is a string array. For my testing I want to test with passing an empty array in my request. However, the assertion in MockHttpServletRequestBuilder.addToMultiValueMap doesn't let me to pass null or empty values.

This is the error body I am getting:

java.lang.IllegalArgumentException: 'values' must not be empty
at org.springframework.util.Assert.notEmpty(Assert.java:214)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.addToMultiValueMap(MockHttpServletRequestBuilder.java:698)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.param(MockHttpServletRequestBuilder.java:153)
at MyMockApiRequests.queryPath(MockJdbcApiRequests.java:105)

Is there any other way to test this condition?

rozagh
  • 73
  • 1
  • 12
  • You probably simply need to avoid passing the parameter if the array is empty, then there should be no parameter with that name in the query string. – JB Nizet Mar 16 '16 at 18:58

1 Answers1

3

I think setting your value to an empty string works.

My Controller

@RequestMapping(value = "/admin/config", method = RequestMethod.GET)
public List<TdConfig> getTdConfigs(@RequestParam(required = false) List<String> names) {
    return tdAdminService.getTdConfigs(names);
}

My Mockito

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("names", "");
    MockHttpServletRequestBuilder request = get("/admin/config")
            .params(params)
            .accept(MediaType.APPLICATION_JSON);

    mockMvc.perform(request)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(print());

Printout of Request:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /admin/config
       Parameters = {names=[]}
          Headers = {Accept=[application/json]}
PCalouche
  • 1,605
  • 2
  • 16
  • 19