如何对具有对象的RequestParam的Controller方法进行单元测试?

问题描述 投票:1回答:1

我有一个控制器映射

@RequestMapping(value = "/something", method = RequestMethod.GET)
public String get(@RequestParam("id") Person aPerson, Model aModel) {

    aModel.addAttribute("person", aPerson);
    return "index";
}

我如何通过MockMvc进行测试?

我可以做这样的事情

mockMvc.perform(get("/something?id=1")).andExpect(status().is2xxSuccessful());

但这不起作用,因为RequestParam是一个对象,而不是一个String。转换是由Spring完成的,但我是单元测试方法,不想启动应用程序上下文。我如何用MockMvc对这样的东西进行单元测试?

java spring mockmvc
1个回答
0
投票

你可能会尝试类似的东西

    @Test
    public void test() throws Exception {
       Model model= new Model();
       mockMvc.perform(MockMvcRequestBuilders.get("/something?id=1")
         .content(asJsonString(model))
         .contentType(MediaType.APPLICATION_JSON)
         .accept(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful());
    }
© www.soinside.com 2019 - 2024. All rights reserved.