ham-sandwich
ham-sandwich

Reputation: 4050

Constant MissingServletRequestParameterException

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:

  1. Using param

    @Test
    public void shouldFetchProducts() throws Exception {
        mockMvc.perform(get("/products")
                .param("ids[]", "[\"item\"]"))
                .andExpect(status().is2xxSuccessful());
    }
    
  2. 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

Answers (2)

Akshay Singh
Akshay Singh

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

mkhanoyan
mkhanoyan

Reputation: 2079

have you tried

@Test
public void shouldFetchProducts() throws Exception {
    mockMvc.perform(get("/products")
            .param("ids", "item1", "item2"))
            .andExpect(status().is2xxSuccessful());
}

Documentation for param can be found here.

Upvotes: 1

Related Questions