【问题标题】:Is there any other way to put parameter of MockMVC?有没有其他方法可以放置 MockMVC 的参数?
【发布时间】:2018-11-02 05:21:22
【问题描述】:

我目前正在使用 Spring MockMvc 和 junit 测试 api 端点。 它适用于以下代码。

    public void testGetMethod(String url, String locale, String empKey, String accessToken) throws Exception {
    mockMvc.perform(get(url).param("locale", locale).param("empKey", empKey).param("accessToken", accessToken))
           .andDo(print())
           .andExpect(status().isOk());
}

但问题是当我试图修改这段代码时 如下(用于稍后使用 .properties 文件设置参数), 我收到 400 条带有消息的代码,“必需的字符串参数 'locale' 不存在”。

    public void testGetMethod_param(String url, String locale, String empKey, String accessToken) throws Exception {
    MultiValueMap<String, Object> paraMap =new LinkedMultiValueMap<>();
    paraMap.add("locale", locale);
    paraMap.add("empKey", empKey);
    paraMap.add("accessToken", accessToken);
    mockMvc.perform(get(url))
    .andDo(print())
    .andExpect(status().isOk());
}

谁能指出我在这里做错了什么?

【问题讨论】:

    标签: unit-testing spring-mvc junit mockito


    【解决方案1】:

    您需要将 paraMap 添加到 get 请求中。

     mockMvc.perform(get(url).params(paraMap))
        .andDo(print())
        .andExpect(status().isOk());
    

    【讨论】:

    • 我应该更新 4.2.4 以上的 Spring Framework 版本以使用 Params。谢谢!问题解决了:D
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多