2013-11-24 62 views
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"); 
} 
+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。