MockMVC-下拉列表中的Form Submit Spring控制器

时间:2018-06-26 04:20:15

标签: ajax spring-mvc mockito mockmvc

任何人都可以协助为控制器编写模拟MVC吗?我想出了模拟MVC,但是我被卡住了,不确定如何进一步测试

从用户界面

  1. 用户从下拉菜单中进行选择,并使用选择ID作为名称提交表单(这是控制器中的@RequestBody字符串名称)

我的控制器

 @PostMapping("/api/user")
public User getSearch(@RequestBody String name) {
    User user=new User();   
    String result=userService.findByUser(name);
    user.setUsername(result);
    return user;

}

我的模拟MVC类

@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Test
public void testUser() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mockMvc.perform(post("/api/user")
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk());
}

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

你很近。不过,您不需要APPLICATION_JSON,因为您只需要传递字符串。

@Autowired
private YourController yourController;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(yourController)
            .build();
}

@Test
public void requestBody() throws Exception {
    this.mockMvc.perform(
            post("/api/user")
                .contentType(MediaType.TEXT_PLAIN)
                .content("foobar")
            .andExpect(status().isOk());

此外,在控制器内的方法中添加@ResponseBody

@Test
public void requestBody() throws Exception {
  this.mockMvc.perform(
    post("/api/user")
    .contentType(MediaType.TEXT_PLAIN)
    .content("foobar")
    .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json"))
    .andExpect(jsonPath("$name", is("foobar")));