gpt4 book ai didi

java - spring-test 和mockito Controller 测试

转载 作者:行者123 更新时间:2023-12-01 04:19:23 25 4
gpt4 key购买 nike

@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 不同)。我该如何修复它?

最佳答案

UserDto 对象需要重写 equals() 方法。

@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}

完成!

关于java - spring-test 和mockito Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19109018/

25 4 0