如何用Mockito测试含try-catch捕获异常的方法(异常捕获场景)
测试sendSuccessEmail方法的异常捕获逻辑(基于Mockito)
要覆盖sendSuccessEmail的try-catch分支,需要通过Mockito模拟sendEmail方法抛出异常,同时验证异常捕获后的日志行为,具体步骤如下:
1. 测试类基础配置
确保测试类使用Mockito扩展,注入待测试实例并mock依赖:
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import jakarta.mail.MessagingException; @ExtendWith(MockitoExtension.class) class EmailServiceImplTest { @InjectMocks private EmailServiceImpl emailServiceImpl; // 待测试的服务类 @Mock private Logger log; // Mock日志对象,用于验证日志输出 @Mock private Ar11ResultBean ar11ResultBean; // Mock业务Bean,按需使用 }
2. 测试异常捕获分支(覆盖catch块)
模拟sendEmail抛出异常,验证sendSuccessEmail能捕获异常并打印日志:
@Test void sendSuccessEmail_WhenSendEmailThrowsException_ShouldLogErrorSilently() throws MessagingException { // 准备测试参数 String smtpHost = "test-host"; Integer smtpPort = 68; String from = "from@test.com"; String to = "to@test.com"; // 模拟sendEmail方法抛出异常(void方法需用doThrow语法) doThrow(MessagingException.class) .when(emailServiceImpl) .sendEmail(smtpHost, smtpPort, from, to, Constants.EMAIL_SUBJECT_SUCCESS, anyString()); // 调用待测试方法 emailServiceImpl.sendSuccessEmail(ar11ResultBean, smtpHost, smtpPort, from, to); // 验证日志是否正确打印异常信息 verify(log).error("AR11 Application: Could not send success email due to error: ", any(MessagingException.class)); }
3. 测试正常流程分支(覆盖try块)
为满足完整代码覆盖率,补充测试正常执行的场景:
@Test void sendSuccessEmail_WhenSendEmailSucceeds_ShouldCallSendEmailCorrectly() throws MessagingException { String smtpHost = "test-host"; Integer smtpPort = 25; String from = "from@test.com"; String to = "to@test.com"; String expectedRows = "100"; // 模拟业务Bean返回数据 when(ar11ResultBean.getRowsProcessed()).thenReturn(expectedRows); // 调用待测试方法 emailServiceImpl.sendSuccessEmail(ar11ResultBean, smtpHost, smtpPort, from, to); // 验证sendEmail被正确调用,参数符合预期 String expectedBody = MessageFormat.format(Constants.EMAIL_BODY_SUCCESS, expectedRows); verify(emailServiceImpl).sendEmail(smtpHost, smtpPort, from, to, Constants.EMAIL_SUBJECT_SUCCESS, expectedBody); }
关键说明
- 针对void方法抛出异常:Mockito对无返回值方法模拟异常需使用
doThrow语法,而非常规的when(...).thenThrow。 - 空Bean场景补充:若需测试
ar11ResultBean为null的情况,只需调用时传入null,验证邮件体是否用空字符串填充即可。 - 日志验证:通过mock的
Logger对象,用verify确认错误日志输出,确保catch块逻辑确实执行。
内容的提问来源于stack exchange,提问作者gene b.
相关产品推荐
相关产品推荐

