如何在 Mockito 中测试 try 和 catch 块?

How do I test a try and catch block in Mockito?

我已经从 Internet 上尝试了很多不同的东西,但还没有发现任何人仅使用 Mockito 来处理 try 和 catch 块的异常。 这是我要测试的代码:

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

    }

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

提前感谢您的帮助:)

你需要为DuplicateEmailExceptionUserAlreadyInsertedException编写单独的测试用例。
如果你有一个正面场景的测试用例就更好了。

第一次考试 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());   
}