95

我正在使用 spring 3.2 mock mvc 来测试我的控制器。我的代码是

 @Autowired
     private Client client;

     @RequestMapping(value = "/user", method = RequestMethod.GET)
        public String initUserSearchForm(ModelMap modelMap) {
            User user = new User();
            modelMap.addAttribute("User", user);
            return "user";
        }

        @RequestMapping(value = "/byName", method = RequestMethod.GET)
        @ResponseStatus(HttpStatus.OK)
        public
        @ResponseBody
        String getUserByName(
           @RequestParam("firstName") String firstName,
           @RequestParam("lastName") String lastName,
           @ModelAttribute("userClientObject") UserClient userClient) {
            return client.getUserByName(userClient, firstName, lastName);
        }

我写了以下测试:

@Test public void testGetUserByName() throws Exception {
        String firstName = "Jack";
        String lastName = "s";       
        this.userClientObject = client.createClient();
        mockMvc.perform(get("/byName")
                .sessionAttr("userClientObject", this.userClientObject)
                .param("firstName", firstName)
                .param("lastName", lastName)               
        ).andExpect(status().isOk())
                .andExpect(content().contentType("application/json"))
                .andExpect(jsonPath("$[0].id").exists())
                .andExpect(jsonPath("$[0].fn").value("Marge"));
}

我得到的是

java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)

为什么会发生这种情况?传递@RequestParam 是否正确

4

3 回答 3

131

当我分析你的代码时。我也面临同样的问题,但我的问题是,如果我为名字和姓氏都赋予价值意味着它工作正常。但是当我只给出一个值时,它表示 400。无论如何使用 .andDo(print()) 方法来找出错误

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

如果您的问题是org.springframework.web.bind.missingservletrequestparameterexception您必须将代码更改为

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }
于 2013-08-01T03:55:48.197 回答
11

如果有人来这个问题寻找同时添加多个参数的方法(我的情况),您可以使用.paramsMultivalueMap不是添加每个.param

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())
于 2019-09-30T20:04:21.847 回答
0

@ModelAttribute是请求参数到特定对象类型的 Spring 映射。所以你的参数可能看起来像userClient.usernameanduserClient.firstName等,因为 MockMvc 模仿来自浏览器的请求,你需要传入 Spring 将从表单中使用的参数来实际构建UserClient对象。

(我认为 ModelAttribute 是一种帮手,可以从表单中的一堆字段中构造一个对象,但是您可能需要阅读一些内容以获得更好的定义)

于 2013-07-31T15:14:36.583 回答