Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 弹簧试验和mockito控制器试验_Java_Mockito_Spring Test - Fatal编程技术网

Java 弹簧试验和mockito控制器试验

Java 弹簧试验和mockito控制器试验,java,mockito,spring-test,Java,Mockito,Spring Test,UserDto是spring mvc表单对象传递的对象 @Test public void testWelcomePage() throws Exception { UserDto dto = new UserDto("admin"); UserEntity user = new UserEntity("admin"); when(userServiceMock.getUser(dto)).thenReturn(user); mockMvc.perform(ge

UserDto是spring mvc表单对象传递的对象

@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);
}
但是,mockito在传递的argumentUserDto id处抛出断言错误。
如何修复它?

UserDto对象需要重写equals方法

@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";
}

完成了

也许您不需要验证,用户在模型中还不够吗?我猜,您在mock语句中期望的UserDto对象whenuservicemock.getUserdto.thenReturnuser;与实际语句userService.GetUserDTO中的UserDto对象不同;这就是为什么它在执行时没有真正模拟实际语句,因此它返回null。执行时传递给实际语句的对象必须与预期时的对象相同,然后只有它才会返回预期的对象
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}