java - 如何在 Mockito 中测试 try and catch 块?
问题描述
我从 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());
}
推荐阅读
- angular - 如何使我的角度路线正常工作
- git - GitLab CE 的高内存使用优化
- python - 从字符串末尾删除并在开头添加新字符?
- parsing - 使用 ELK 中的摄取节点处理器以 yyyy.MM.dd HH.mm.ss.SSSSSS 格式解析日期
- python - 从相似度矩阵创建 NetworkX 图
- centos - 错误'bad pad value "2m": must be positive screen distance' when using tk_messageBox on a wayland display (CentOS)
- arm - 使用 ARM M0 和 GDB 进行监控模式调试
- elasticsearch - 当我们在弹性搜索中使用倒排索引并获取包含特定单词/单词的所有文档时,在搜索中使用正向索引有什么用?
- python - 如何在 SciPy 正交距离回归 (ODR) 中使用 Lambda 函数?
- c# - C# ASP.NET Core Web API 包含在哪里