1
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();
}
}
現在這是我的一個test.it是當改變Pasword成功。我如何測試更新方法使用Junit
@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");
}
我不會更改生產代碼以獲得測試運行... –