![](/img/trans.png)
[英]How do I write a unit test for a controller class that has a Post method?
[英]How to unit test a Controller method that has a RequestParam of an object?
我有一個控制器映射
@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進行單元測試?
您可以嘗試類似
@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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.