
本文旨在解决使用junit5和mockito测试java服务中内部依赖(如guava loadingcache)抛出并处理的异常(特别是catch块覆盖率)的挑战。核心策略是采用依赖注入模式,通过引入工厂接口或自定义包装器类来解耦服务与缓存的直接创建,从而使缓存实例在测试中可被模拟。文章将详细介绍两种实现方式及其对应的测试代码,确保`executionexception`的`catch`块能够被有效覆盖,提升代码测试的完整性。
在开发高健壮性的Java应用时,我们经常会遇到需要处理内部组件抛出的异常场景。然而,当这些组件在服务类内部直接实例化时,对其异常处理逻辑进行单元测试,特别是覆盖catch块,会变得极具挑战。本教程将以一个具体的案例为例,探讨如何利用JUnit5和Mockito,通过引入依赖注入(Dependency Injection)模式,有效测试一个void方法中由LoadingCache引起的ExecutionException的catch块。
考虑以下MyService类中的unlockFailed方法:
public class MyService {
private LoadingCache<String, Integer> attemptsCache;
public MyService() {
super();
// 缓存直接在构造函数中实例化
attemptsCache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnits.HOURS)
.build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) throws Exception {
return 0;
}
});
}
public void unlockFailed(String key) {
int attempts = 0;
try {
attempts = attemptsCache.get(key); // 这里的get方法可能抛出ExecutionException
} catch (ExecutionException e) {
attempts = 0; // 目标:覆盖这个catch块
}
attempts++;
attemptsCache.put(key, attempts);
}
}在上述代码中,MyService内部直接创建并持有一个LoadingCache实例。unlockFailed方法尝试从缓存中获取值,并包含一个try-catch块来处理可能发生的ExecutionException。传统的单元测试尝试通过Mockito.doThrow().when(attemptsCache).get(USER);来模拟异常,但由于attemptsCache是在MyService内部创建的真实对象,而非注入的模拟对象,因此这种模拟无法生效,导致catch块始终无法被覆盖。
问题的核心在于MyService与LoadingCache的紧密耦合。为了实现可测试性,我们需要解耦它们,使得在测试时可以注入一个模拟的LoadingCache。
依赖注入是解决此类问题的关键。通过将LoadingCache的创建或实例本身作为依赖项注入到MyService中,我们就可以在测试环境中提供一个由Mockito创建的模拟对象。下面介绍两种常用的依赖注入实现方式。
这种方法通过引入一个工厂接口来抽象LoadingCache的创建过程。MyService不再直接创建缓存,而是通过工厂获取。
1. 定义缓存工厂接口和实现类
// CacheFactory.java
public interface CacheFactory {
LoadingCache<String, Integer> createCache();
}
// ExpiringCacheFactory.java (生产环境实现)
public class ExpiringCacheFactory implements CacheFactory {
@Override
public LoadingCache<String, Integer> createCache() {
return CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) throws Exception {
return 0;
}
});
}
}2. 修改 MyService 构造函数
MyService现在通过构造函数接收CacheFactory实例。
// MyService.java (修改后)
public class MyService {
private LoadingCache<String, Integer> attemptsCache;
public MyService(final CacheFactory cacheFactory) { // 注入CacheFactory
super();
this.attemptsCache = cacheFactory.createCache(); // 通过工厂创建缓存
}
// unlockFailed 方法保持不变
public void unlockFailed(String key) {
int attempts = 0;
try {
attempts = attemptsCache.get(key);
} catch (ExecutionException e) {
attempts = 0;
}
attempts++;
attemptsCache.put(key, attempts);
}
}3. 生产环境中的使用
final MyService myService = new MyService(new ExpiringCacheFactory());
4. 单元测试代码
在测试中,我们可以提供一个匿名CacheFactory实现,它返回一个由Mockito模拟的LoadingCache。
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ExecutionError;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.*;
public class MyServiceTest {
private final String USER = "fakeuser";
@DisplayName("unlockFailed 应该在 LoadingCache.get 抛出 ExecutionException 时处理异常")
@Test
public void unlockFailed_should_handle_ExecutionException_with_factory() throws ExecutionException {
// Arrange
// 1. 模拟 LoadingCache
LoadingCache<String, Integer> attemptsCacheMock = Mockito.mock(LoadingCache.class);
// 2. 配置模拟缓存,使其在调用get方法时抛出ExecutionException
doThrow(new ExecutionException("Dummy ExecutionException", null)).when(attemptsCacheMock).get(USER);
// 3. 创建 MyService 实例,注入一个返回模拟缓存的工厂
// 这里使用 lambda 表达式简化匿名内部类
MyService sut = new MyService(() -> attemptsCacheMock);
// Act
sut.unlockFailed(USER);
// Assert
// 验证 attemptsCache.get(USER) 方法被调用了一次
verify(attemptsCacheMock, times(1)).get(USER);
// 验证 attemptsCache.put(USER, 0) 方法被调用了一次 (因为catch块将attempts重置为0)
verify(attemptsCacheMock, times(1)).put(USER, 1); // attempts = 0 + 1 = 1
// 注意:这里不需要断言抛出异常,因为方法内部已经捕获并处理了
}
}通过这种方式,MyService在测试时使用的是一个完全受控的模拟LoadingCache,我们可以轻松地模拟get()方法抛出ExecutionException,从而覆盖到catch块的逻辑。
如果LoadingCache的接口过于复杂,或者我们只想暴露其一部分方法,可以创建一个自定义接口来包装LoadingCache,并将其注入到MyService中。
1. 定义自定义缓存接口和实现类
// MyLoadingCache.java
public interface MyLoadingCache {
// 暴露 LoadingCache 中需要用到的方法
Integer get(String key) throws ExecutionException;
void put(String key, Integer value);
}
// MyLoadingCacheImpl.java (生产环境实现)
public class MyLoadingCacheImpl implements MyLoadingCache {
private LoadingCache<String, Integer> attemptsCache;
public MyLoadingCacheImpl() {
this.attemptsCache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) throws Exception {
return 0;
}
});
}
@Override
public Integer get(String key) throws ExecutionException {
return attemptsCache.get(key);
}
@Override
public void put(String key, Integer value) {
attemptsCache.put(key, value);
}
}2. 修改 MyService 构造函数
MyService现在直接接收MyLoadingCache接口实例。
// MyService.java (修改后)
public class MyService {
private MyLoadingCache attemptsCache; // 使用自定义接口类型
public MyService(final MyLoadingCache attemptsCache) { // 注入自定义缓存接口
super();
this.attemptsCache = attemptsCache;
}
// unlockFailed 方法保持不变
public void unlockFailed(String key) {
int attempts = 0;
try {
attempts = attemptsCache.get(key);
} catch (ExecutionException e) {
attempts = 0;
}
attempts++;
attemptsCache.put(key, attempts);
}
}3. 生产环境中的使用
final MyService myService = new MyService(new MyLoadingCacheImpl());
4. 单元测试代码
测试时,我们可以直接模拟MyLoadingCache接口。
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.ExecutionException;
import static org.mockito.Mockito.*;
public class MyServiceTest {
private final String USER = "fakeuser";
@DisplayName("unlockFailed 应该在 MyLoadingCache.get 抛出 ExecutionException 时处理异常")
@Test
public void unlockFailed_should_handle_ExecutionException_with_wrapper() throws ExecutionException {
// Arrange
// 1. 模拟 MyLoadingCache 接口
MyLoadingCache cacheMock = Mockito.mock(MyLoadingCache.class);
// 2. 配置模拟缓存,使其在调用get方法时抛出ExecutionException
doThrow(new ExecutionException("Dummy ExecutionException", null)).when(cacheMock).get(USER);
// 3. 创建 MyService 实例,注入模拟缓存
MyService sut = new MyService(cacheMock);
// Act
sut.unlockFailed(USER);
// Assert
// 验证 cacheMock.get(USER) 方法被调用了一次
verify(cacheMock, times(1)).get(USER);
// 验证 cacheMock.put(USER, 0) 方法被调用了一次
verify(cacheMock, times(1)).put(USER, 1);
}
}在某些情况下,如果LoadingCache的创建逻辑不复杂,或者我们接受直接注入Guava的LoadingCache接口,也可以选择直接将LoadingCache<String, Integer>作为依赖注入。
// MyService.java (直接注入LoadingCache)
public class MyService(final LoadingCache<String, Integer> attemptsCache) {
super();
this.attemptsCache = attemptsCache;
}这种方式最直接,但需要确保LoadingCache的实际创建逻辑(如CacheLoader的定义)可以被外部管理或在生产环境中通过其他方式(如Spring的@Bean)提供。
通过引入依赖注入模式,无论是通过缓存工厂还是自定义缓存包装器,我们都成功地将MyService与LoadingCache的具体实现解耦。这不仅解决了在单元测试中模拟内部依赖并覆盖异常处理块的难题,更重要的是,它提升了代码的设计质量和可维护性。在未来的开发中,应优先考虑使用依赖注入来管理类之间的协作关系,以构建更健壮、更易于测试的应用程序。
以上就是JUnit5/Mockito:优雅测试内部依赖与异常处理的实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号