我使用彈簧3.2模擬MVC來測試我controller.My代碼模擬MVC - 添加請求參數測試
@Autowired
private Client client;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String initUserSearchForm(ModelMap modelMap) {
User user = new User();
modelMap.addAttribute("User", user);
return "user";
}
@RequestMapping(value = "/byName", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
String getUserByName(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName, @ModelAttribute("userClientObject") UserClient userClient) {
return client.getUserByName(userClient, firstName, lastName);
}
,我寫了下面的測試:
@Test
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
我所得到的是
java.lang.AssertionError: Status expected:<200> but was:<400>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
爲什麼會發生這種情況?是它傳遞@RequestParam
我寫了相同的代碼,但是有問題的ModelAttribute混淆。請閱讀http://stackoverflow.com/questions/19427341/why-modelatribute-passed-as-null – gstackoverflow
很好的前端與'andDo(打印())',非常實用! –
記事,'打印()''是MockMvcResultHandlers'類的方法 – WildDev