春天测试postmapping与params

时间:2018-03-10 13:04:03

标签: java spring mockito

任何人都可以告诉我如何使用Mockito

在我的控制器中测试这个指定的方法
@RequestMapping(value = "categories", params = {"save"}, method = RequestMethod.POST)
    public String newCategory(@Valid Category category){
        categoriesService.save(category);
        return "redirect:categories";
    }

我尝试这样做,但我获取的是HTTP状态代码400而不是302,而且我不知道如何创建正确的请求来测试此映射

this.mockMvc
                .perform(post("/categories")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .sessionAttr("category", new Category()))
                .andExpect(status().isFound())
                .andExpect(redirectedUrl("categories"));

修改

好的,我已将测试更改为此表单,现在它正在为我工​​作。

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("name", "test");
        params.add("save", "save");
        this.mockMvc
                .perform(post("/manager/categories")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .params(params))
                .andExpect(status().isFound())
                .andExpect(redirectedUrl("categories"));

0 个答案:

没有答案
相关问题