![](/img/trans.png)
[英]How to mock and write unit test for try and catch block using mockito
[英]How do I test a try and catch block in Mockito?
我从 Internet 上尝试了很多不同的东西,但没有发现任何异常处理 try and catch 仅使用 Mockito 块。 这是我要测试的代码:
public void add() throws IOException {
try {
userDAO.insert(user);
externalContext.redirect("users.xhtml");
} catch (final DuplicateEmailException e) {
final FacesMessage msg = new FacesMessage(
"Die E-Mail Adresse wird bereits verwendet.");
facesContext.addMessage(emailInput.getClientId(), msg);
} catch (final UserAlreadyInsertedException e) {
throw new IllegalStateException(e);
}
}
然后这就是我现在尝试测试的方式:
@Test
public void addTest() throws IOException, UserAlreadyInsertedException, DuplicateEmailException {
User user = mock(User.class);
doNothing().when(userDAO).insert(user);
doNothing().when(externalContext).redirect(anyString());
doNothing().when(facesContext).addMessage(anyString(),any());
try{
initMirror();
userAddBean.add();
verify(userDAO, times(1)).insert(user);
verify(externalContext, times(1)).redirect(anyString());
}
catch (DuplicateEmailException e){
verify(facesContext,times(1)).addMessage(anyString(),any());
}
catch (UserAlreadyInsertedException e){
doThrow(IllegalStateException.class);
}
}
我很确定,尤其是我尝试捕获并抛出异常的最后一部分是错误的,但我真的找不到一个很好的教程。
在此先感谢您的帮助:)
您需要为DuplicateEmailException
和UserAlreadyInsertedException
编写单独的测试用例。
如果您有一个正面场景的测试用例,那就太好了。
DuplicateEmailException
的第一个测试
@Test
public void addTestForDuplicateEmailException() throws IOException, UserAlreadyInsertedException, DuplicateEmailException {
User user = mock(User.class);
doNothing().when(externalContext).redirect(anyString());
doNothing().when(facesContext).addMessage(anyString(),any());
Mockito.when(userDAO.insert(Mockito.any(User.class))).thenThrow(new DuplicateEmailException());
initMirror();
userAddBean.add();
verify(userDAO, times(1)).insert(user);
verify(externalContext, times(1)).redirect(anyString());
}
UserAlreadyInsertedException
的第二次测试
@Test
public void addTestForUserAlreadyInsertedException() throws IOException, UserAlreadyInsertedException, DuplicateEmailException {
User user = mock(User.class);
doNothing().when(externalContext).redirect(anyString());
doNothing().when(facesContext).addMessage(anyString(),any());
Mockito.when(userDAO.insert(Mockito.any(User.class))).thenThrow(new UserAlreadyInsertedException());
initMirror();
userAddBean.add();
verify(userDAO, times(1)).insert(user);
verify(externalContext, times(0)).redirect(anyString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.