Reputation: 4050
For some reason, I continously get the error message:
MissingServletRequestParameterException: Required String[] parameter 'ids' is not present
I have an endpoint which can be called from /products?ids=["item1", "item2"]
My integration test class looks like so:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(MockitoJUnitRunner.class)
public class ProductControllerTest {
private MockMvc mockMvc;
@InjectMocks
private ProductController controller;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.param("ids[]", "[\"item\"]"))
.andExpect(status().is2xxSuccessful());
}
}
What I've tried:
Using param
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.param("ids[]", "[\"item\"]"))
.andExpect(status().is2xxSuccessful());
}
Using requestAttr
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.requestAttr("ids[]", "[\"item\"]"))
.andExpect(status().is2xxSuccessful());
}
What am I doing wrong?
Upvotes: 0
Views: 564
Reputation: 93
Try using a MultiValueMap
for this:
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("ids", "item1");
params.add("ids", "item2");
Now when you write your test-case, use the following:
mockMvc.perform(get("/products")
.params(params))
.andExpect(status().is2xxSuccessful());
Upvotes: 0