【发布时间】:2013-10-01 05:58:29
【问题描述】:
@Test
public void testWelcomePage() throws Exception {
UserDto dto = new UserDto("admin");
UserEntity user = new UserEntity("admin");
when(userServiceMock.getUser(dto)).thenReturn(user);
mockMvc.perform(get("/main/user/welcome?loginId=admin"))
.andExpect(status().isOk())
.andExpect(view().name("user/welcome"))
.andExpect(forwardedUrl("/WEB-INF/pages/user/welcome.jsp"))
.andExpect(model().attribute("user", hasProperty("loginId", is("admin")))); //-->java.lang.AssertionError: Model attribute 'user' .... but: was null...
verify(userServiceMock, times(1)).getUser(dto); //-->Argument(s) are different! Wanted:
verifyNoMoreInteractions(userServiceMock);
}
UserDto 是 spring mvc 表单对象传递的对象。
@RequestMapping(value="/welcome", method = RequestMethod.GET)
public String welcome(UserDto userDto, ModelMap model, Locale locale) {
UserEntity user = null;
try {
user = userService.getUser(userDto);
} catch (DataNotFoundException e) {
e.printStackTrace();
model.addAttribute("message", messageSource.getMessage("msg.data.notfound", null, locale));
}
model.addAttribute("user", user);
return "user/welcome";
}
但是,mockito 在传递的参数处抛出断言错误(UserDto id 不同)。 我该如何解决?
【问题讨论】:
-
也许你不需要验证,
user在模型中还不够吗? -
我猜,你在模拟语句中期望的 UserDto 对象 when(userServiceMock.getUser(dto)).thenReturn(user);与实际语句 userService.getUser(userDto) 中的 UserDto 对象不同;这就是为什么它在执行时并没有真正模拟实际的语句,因此它返回 null。执行时传递给实际语句的对象必须与期望时的对象相同,然后才会返回您期望的对象
标签: java mockito spring-test