出于某种原因,我不断收到错误消息:
MissingServletRequestParameterException:必需的String []参数 “ids”不存在
我有一个可以从/products?ids=["item1", "item2"]
我的集成测试类看起来像这样:
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());
}
}
我尝试了什么:
使用 param
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.param("ids[]", "[\"item\"]"))
.andExpect(status().is2xxSuccessful());
}
使用 requestAttr
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.requestAttr("ids[]", "[\"item\"]"))
.andExpect(status().is2xxSuccessful());
}
我做错了什么?
答案 0 :(得分:1)
你试过吗
@Test
public void shouldFetchProducts() throws Exception {
mockMvc.perform(get("/products")
.param("ids", "item1", "item2"))
.andExpect(status().is2xxSuccessful());
}
可以找到param
的文档here。
答案 1 :(得分:0)
尝试使用MultiValueMap
:
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("ids", "item1");
params.add("ids", "item2");
现在,当您编写测试用例时,请使用以下命令:
mockMvc.perform(get("/products")
.params(params))
.andExpect(status().is2xxSuccessful());