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 函数编程中异常处理的单元测试策略是什么?详情请关注图灵教育的其他相关文章!