java 函数式编程中处理异常的单元测试策略包括四种方法:使用 assertthrows 断言异常类型。使用 try-with-resources 语句处理资源清理。使用 assertthatthrownby 断言异常类型和消息。使用 exceptionrule 规则处理异常并验证错误消息。

Java 函数式编程中异常处理的单元测试策略
函数式编程中异常处理的一个常见策略是捕获异常并将其转换为一个新的值或效果。这种方法有助于保持代码的可组合性和不变性。为了单元测试此类代码,我们可以使用以下策略:
1. 使用 assertThrows 断言
立即学习“Java免费学习笔记(深入)”;
assertThrows 方法允许我们断言特定异常类型在执行代码块时会被抛出,如下所示:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MyFunctionalService {
T handleCheckedException(Function<T, T> function) {
try {
return function.apply(null);
} catch (Exception e) {
return handleUnexpectedException(e);
}
}
T handleUnexpectedException(Exception e) {
// Handle the exception
return null;
}
}
class MyFunctionalServiceTest {
@Test
void shouldHandleCheckedException() {
MyFunctionalService service = new MyFunctionalService();
assertThrows(NullPointerException.class, () ->
service.handleCheckedException(t -> t.toString())
);
}
}2. 使用 try-with-resources 语句
try-with-resources 语句可以自动处理资源清理,包括关闭可关闭对象和捕获异常。这简化了对可能抛出异常的代码的测试,如下所示:
class MyService {
void closeableOperation() throws IOException {
try (CloseableResource resource = new CloseableResource()) {
// Do something
}
}
}
class MyServiceTest {
@Test
void shouldHandleCloseableOperationException() throws IOException {
MyService service = new MyService();
try (CloseableResource mockResource = Mockito.mock(CloseableResource.class)) {
Mockito.when(mockResource.close()).thenThrow(new IOException());
service.closeableOperation();
} catch (IOException e) {
// Assert something
}
}
}3. 使用 assertThatThrownBy 断言
assertThatThrownBy 断言允许我们验证代码块抛出的异常的类型和消息。这适用于必须抛出特定异常甚至具有特定消息的场景,如下所示:
class MyService {
int calculate(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Both arguments must be non-negative.");
}
return a + b;
}
}
class MyServiceTest {
@Test
void shouldThrowExceptionWithCorrectMessage() {
assertThatThrownBy(() -> myService.calculate(-1, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Both arguments must be non-negative.");
}
}4. 使用 exceptionRule 规则
exceptionRule 规则可以处理测试方法中的异常,并且可以在需要记录异常或验证特定的错误消息时使用。注意,此方法略显过时,建议首选 assertThrows 或 assertThatThrownBy 断言,如下所示:
interface MyRule {
void verifyExpectedException(Throwable throwable);
}
@Rule
public MyRule exceptionRule = new MyRule() {
@Override
public void verifyExpectedException(Throwable throwable) {
// Verify the exception
}
};
class MyServiceTest {
@Test
public void shouldHandleCheckedException() throws IOException {
// Do something that may throw an IOException
}
}以上就是Java 函数式编程中异常处理的单元测试策略是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号