
本文旨在指导开发者如何有效地单元测试Java中包含异常捕获块(`catch`)和异常适配器(`ExceptionAdapter`)的代码。我们将深入探讨在模拟(mocking)异常适配器行为时常见的误区,特别是区分方法是抛出异常还是返回异常对象,并提供正确的测试策略和代码示例,确保异常处理逻辑得到充分覆盖和验证。
理解异常捕获与适配器模式
在现代软件开发中,为了更好地管理和转换不同类型的异常,我们经常会引入异常适配器模式。当底层服务抛出特定异常时,适配器负责将其转换为上层服务预期的异常类型。以下是一个典型的Java方法,其中包含一个try-catch块,并在catch块中使用了serviceExceptionAdapter来处理捕获到的异常:
public Method execute(@NonNull final String test) throws ServiceException {
Object object;
try {
object = javaClient.fetchInfo(test);
} catch (ClientException | InternalServerError e) {
// 异常适配器将捕获到的异常转换为ServiceException并抛出
throw serviceExceptionAdapter.apply(e);
}
return object;
}在这个execute方法中,javaClient.fetchInfo(test)可能会抛出ClientException或InternalServerError。当这些异常被捕获时,serviceExceptionAdapter.apply(e)会被调用。根据方法签名,apply方法预期会接收一个异常对象e,并返回一个ServiceException的实例,然后这个返回的ServiceException会被execute方法抛出。
单元测试异常捕获块的挑战
单元测试上述catch块的关键在于,如何正确模拟javaClient抛出异常,并验证serviceExceptionAdapter被调用且其返回值被正确地抛出。一个常见的错误是在模拟serviceExceptionAdapter.apply()方法时,将其设置为抛出异常,而不是返回异常对象。
考虑以下初始的测试尝试:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class ProxyTest {
private ExceptionAdapter serviceExceptionAdapter;
private JavaClient mockJavaClient;
private Proxy proxy;
@BeforeEach
void setup() {
this.serviceExceptionAdapter = mock(ExceptionAdapter.class);
this.mockJavaClient = mock(JavaClient.class);
proxy = new Proxy(mockJavaClient, serviceExceptionAdapter);
}
@Test
void test_InternalServerError_IncorrectMocking() {
String testParam = "someTestValue";
// 模拟javaClient抛出InternalServerError
when(mockJavaClient.fetchInfo(any())).thenThrow(InternalServerError.class);
// 错误:模拟serviceExceptionAdapter.apply(any())抛出ServiceException
// 而不是返回ServiceException实例
when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);
// 验证execute方法是否抛出ServiceException
assertThrows(ServiceException.class, () -> proxy.execute(testParam));
// 验证serviceExceptionAdapter.apply方法是否被调用一次
verify(serviceExceptionAdapter, times(1)).apply(any());
}
}在test_InternalServerError_IncorrectMocking测试中,when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);这一行存在问题。
分析错误与正确模拟策略
核心问题在于对serviceExceptionAdapter.apply(e)行为的误解。回顾原始代码:
throw serviceExceptionAdapter.apply(e);
这行代码明确表示,serviceExceptionAdapter.apply(e)方法会返回一个ServiceException实例,然后这个返回的实例才会被throw关键字抛出。
然而,在错误的测试中,when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);指示Mockito,当调用serviceExceptionAdapter.apply()时,它应该直接抛出一个ServiceException,而不是返回一个。这与被测试代码的实际逻辑不符,可能导致测试覆盖率不完整,或者在更复杂的场景中出现意料之外的行为。
正确的模拟策略是让serviceExceptionAdapter.apply()方法返回一个ServiceException的实例,就像它在实际运行中那样。
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
// 假设 ServiceException 是一个自定义异常
class ServiceException extends RuntimeException {
public ServiceException(String message) {
super(message);
}
public ServiceException(Throwable cause) {
super(cause);
}
}
// 假设 ExceptionAdapter 接口定义
interface ExceptionAdapter {
ServiceException apply(Throwable e);
}
// 假设 JavaClient 接口定义
interface JavaClient {
Object fetchInfo(String test) throws ClientException, InternalServerError;
}
// 假设 ClientException 和 InternalServerError 是自定义异常
class ClientException extends RuntimeException {}
class InternalServerError extends RuntimeException {}
// 被测试的 Proxy 类
class Proxy {
private final JavaClient javaClient;
private final ExceptionAdapter serviceExceptionAdapter;
public Proxy(JavaClient javaClient, ExceptionAdapter serviceExceptionAdapter) {
this.javaClient = javaClient;
this.serviceExceptionAdapter = serviceExceptionAdapter;
}
public Object execute(final String test) throws ServiceException {
Object object;
try {
object = javaClient.fetchInfo(test);
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
return object;
}
}
class ProxyTest {
private ExceptionAdapter serviceExceptionAdapter;
private JavaClient mockJavaClient;
private Proxy proxy;
@BeforeEach
void setup() {
this.serviceExceptionAdapter = mock(ExceptionAdapter.class);
this.mockJavaClient = mock(JavaClient.class);
proxy = new Proxy(mockJavaClient, serviceExceptionAdapter);
}
@Test
void test_InternalServerError_CorrectMocking() {
String testParam = "someTestValue";
InternalServerError caughtException = new InternalServerError();
ServiceException expectedServiceException = new ServiceException("Adapted from InternalServerError", caughtException);
// 1. 模拟javaClient.fetchInfo()抛出InternalServerError
when(mockJavaClient.fetchInfo(any())).thenThrow(caughtException);
// 2. 模拟serviceExceptionAdapter.apply()返回一个ServiceException实例
// 注意:这里使用thenReturn()而不是thenThrow()
when(serviceExceptionAdapter.apply(caughtException)).thenReturn(expectedServiceException);
// 3. 验证proxy.execute()是否抛出正确的ServiceException
ServiceException actualException = assertThrows(ServiceException.class, () -> proxy.execute(testParam));
assertEquals(expectedServiceException, actualException); // 验证抛出的异常是预期的实例
// 4. 验证serviceExceptionAdapter.apply()方法是否被调用一次,并传入了正确的异常
verify(serviceExceptionAdapter, times(1)).apply(caughtException);
// 5. 验证javaClient.fetchInfo()方法是否被调用一次
verify(mockJavaClient, times(1)).fetchInfo(testParam);
}
@Test
void test_ClientException_CorrectMocking() {
String testParam = "anotherTestValue";
ClientException caughtException = new ClientException();
ServiceException expectedServiceException = new ServiceException("Adapted from ClientException", caughtException);
when(mockJavaClient.fetchInfo(any())).thenThrow(caughtException);
when(serviceExceptionAdapter.apply(caughtException)).thenReturn(expectedServiceException);
ServiceException actualException = assertThrows(ServiceException.class, () -> proxy.execute(testParam));
assertEquals(expectedServiceException, actualException);
verify(serviceExceptionAdapter, times(1)).apply(caughtException);
verify(mockJavaClient, times(1)).fetchInfo(testParam);
}
}在上述修正后的测试中,我们现在使用when(serviceExceptionAdapter.apply(caughtException)).thenReturn(expectedServiceException);。这确保了当serviceExceptionAdapter.apply()被调用时,它会返回一个我们预设的ServiceException实例,从而与被测试代码的逻辑完全匹配。assertThrows随后会捕获到这个由execute方法抛出的ServiceException,并且我们可以进一步使用assertEquals来验证捕获到的异常就是我们期望的那个实例。
注意事项与最佳实践
- 区分thenThrow()与thenReturn(): 这是解决此类问题的关键。如果被测试的方法是return someObject;,那么模拟时应使用thenReturn(someObject);如果被测试的方法是throw someException;,那么模拟时应使用thenThrow(someException)。
- 理解SUT(System Under Test)行为: 在编写测试之前,务必清晰地理解被测试代码的每一行行为,特别是方法调用和异常流。
- 精确匹配参数: 在when(mockObject.method(argument)).thenReturn(...)中,如果可能,尽量使用具体的参数值而不是any(),这样可以更精确地验证方法调用。例如,在我们的例子中,我们模拟了serviceExceptionAdapter.apply(caughtException),确保适配器接收到的是我们期望的原始异常。
- 验证交互: 使用verify()来确认被测方法是否按预期与它的依赖(如serviceExceptionAdapter和javaClient)进行了交互,包括调用次数和传入的参数。
- 测试所有异常路径: 如果catch块处理多种异常类型(如ClientException | InternalServerError),应为每种类型编写独立的测试用例,以确保所有路径都被覆盖。
总结
正确单元测试包含异常捕获和适配器模式的代码需要对模拟框架(如Mockito)有深入的理解,并准确把握被测试代码的执行逻辑。核心在于区分一个方法是“抛出”异常还是“返回”异常对象。通过使用thenReturn()来模拟异常适配器返回一个异常实例,我们可以确保测试准确反映代码的实际行为,从而提高测试的有效性和覆盖率。遵循这些最佳实践,将有助于构建更健壮、更可靠的应用程序。










