在 Java 项目开发过程中,当业务逻辑涉及文件读写、网络请求等操作时,经常会抛出 IOException 并在对应的捕获块中处理异常逻辑,比如记录错误日志、返回默认结果等。为了保证这些异常处理逻辑的正确性,我们需要通过 JUnit 5 编写单元测试来验证捕获块是否按预期执行。

基础测试场景示例
首先我们来看一个包含 IOException 捕获块的待测试业务类,该类的作用是读取文件内容,当文件不存在时会抛出 IOException 并在捕获块中返回默认内容。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileReaderService {
public String readFileContent(String filePath) {
try {
// 读取文件内容,文件不存在时会抛出IOException
return Files.readString(Paths.get(filePath));
} catch (IOException e) {
// 捕获块逻辑:返回默认内容
return "default_content";
}
}
}
使用 JUnit 5 测试捕获块
JUnit 5 提供了 assertThrows 方法用于验证异常是否抛出,但如果要测试捕获块内部的逻辑,我们不需要让测试方法感知到异常,只需要模拟触发异常的场景,然后验证捕获块执行后的返回结果即可。
编写测试用例
我们可以传入一个不存在的文件路径,触发业务方法中的 IOException,然后断言返回结果是否为捕获块中定义的默认内容。
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FileReaderServiceTest {
private final FileReaderService fileReaderService = new FileReaderService();
@Test
void testReadFileContent_WhenIOExceptionThrown_ShouldReturnDefaultContent() {
// 传入不存在的文件路径,触发IOException
String result = fileReaderService.readFileContent("not_exist_file.txt");
// 验证捕获块执行后返回的结果
assertEquals("default_content", result);
}
}
模拟复杂捕获块逻辑的测试
如果捕获块中包含更复杂的逻辑,比如调用其他方法、修改状态等,我们同样可以通过触发异常的方式验证这些逻辑是否执行。下面是一个捕获块中记录错误日志的示例。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FileReaderServiceV2 {
private final List<String> errorLogs = new ArrayList<>();
public String readFileContent(String filePath) {
try {
return Files.readString(Paths.get(filePath));
} catch (IOException e) {
// 捕获块逻辑:记录错误日志并返回默认内容
errorLogs.add("文件读取失败:" + filePath);
return "default_content";
}
}
public List<String> getErrorLogs() {
return errorLogs;
}
}
对应的测试用例需要同时验证返回结果和错误日志是否被正确记录:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
public class FileReaderServiceV2Test {
private final FileReaderServiceV2 fileReaderServiceV2 = new FileReaderServiceV2();
@Test
void testReadFileContent_WhenIOExceptionThrown_ShouldRecordErrorLog() {
String result = fileReaderServiceV2.readFileContent("not_exist_file.txt");
// 验证返回结果
assertEquals("default_content", result);
// 验证捕获块中记录的错误日志
List<String> errorLogs = fileReaderServiceV2.getErrorLogs();
assertEquals(1, errorLogs.size());
assertEquals("文件读取失败:not_exist_file.txt", errorLogs.get(0));
}
}
注意事项
- 测试捕获块时不需要在测试方法中声明抛出 IOException,因为异常已经被业务方法内部的捕获块处理了。
- 如果需要测试捕获块中异常对象的相关信息,比如异常消息,可以在业务方法中将异常信息暂存,或者通过其他方式暴露出来再进行断言。
- 如果捕获块中只是重新抛出异常,那么可以使用
assertThrows来验证异常是否被正确抛出。
JUnit_5IOException单元测试捕获块修改时间:2026-07-06 02:15:22