任何人都可以协助为控制器编写模拟MVC吗?我想出了模拟MVC,但是我被卡住了,不确定如何进一步测试
从用户界面
我的控制器
@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());
}
任何帮助都会很棒
答案 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")));