首页 > 解决方案 > 如何在 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);
        }

    }

我很确定,尤其是我尝试捕获并抛出异常的最后一部分是错误的,但我真的找不到一个很好的教程。

在此先感谢您的帮助:)

标签: javamockito

解决方案


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());   
}

推荐阅读