public boolean changePassword(User user, String newpass) {
user.setPasswordHash(newpass);
if(update(user) == false)
return false;
return true;
}
public boolean update(User user){
SqlSession session = factory.openSession()
try {
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.update(user);
session.commit();
return true;
}catch (Exception e){
e.getMessage();
return false;
}
finally {
session.close();
}
}
现在这是我的一个测试。当改变Pasword Success时。
@Test
public void shouldChangeUserPasswordWhenAsked() {
User updatedUser = new User();
updatedUser.setUserName("user");
updatedUser.setPasswordHash("newpassword");
when(userMapper.findByUsername("user")).thenReturn(updatedUser);
Boolean updateResult = userService.password(user,"newpassword");
verify(userMapper).update(user);
assertEquals("updatedUserSuccess",userService.getByUsername(user.getUserName()).getPasswordHash(),"newpassword");
assertEquals("updatedSuccess",updateResult,true);
}
现在我想如何测试失败的情况,我该怎么做?我应该更改我的更新方法吗?在测试之前我模拟dabase和一些方法依赖于像这样的数据库
@Before
public void setup(){
session = mock(SqlSession.class);
userMapper = mock(UserMapper.class);
userRoleMapper = mock(UserRoleMapper.class);
sessionFactory = mock(SqlSessionFactory.class);
when(sessionFactory.openSession()).thenReturn(session);
when(session.getMapper(UserMapper.class)).thenReturn(userMapper);
when(session.getMapper(UserRoleMapper.class)).thenReturn(userRoleMapper);
userService = new UserServiceImpl(sessionFactory);
user = new User();
user.setUserName("user");
user.setPasswordHash("password");
}
答案 0 :(得分:2)
告诉你的一个模拟在调用时抛出异常:
when(userRoleMapper.update(user)).thenThrow(new RuntimeException("test exception"));
或者,如果update()
方法返回void
:
doThrow(new RuntimeException("test exception")).when(userRoleMapper).update(user);
Mockito有very good documentation。阅读它。
请注意,捕获异常是一种非常糟糕的做法,并且您的方法可能应该让异常冒泡而不是捕获它们并返回false。