首页 > 解决方案 > 如何使用 cache2k 对过滤器进行单元测试

问题描述

我有一个使用缓存的 servlet 过滤器,代码基本上是这样的

public class CustomFilter implements Filter {
    private  final Cache<String, ClientRequest> cache;
    @Autowired
    public CustomFilter(Service service){
    cache = Caching.getCachingProvider().getCacheManager()
            .createCache("requestsCache", 
            ExtendedMutableConfiguration.of(
                    Cache2kBuilder.of(String.class, 
            ClientRequest.class).entryCapacity(100)                                
            .expireAfterWrite(1000, TimeUnit.SECONDS)));
    }
}

关于如何在使用此类的此过滤器中对方法进行单元测试的任何想法?提前致谢,

标签: javaunit-testingcache2k

解决方案


将创建提取Cache<String, ClientRequest>到外部配置并通过过滤器构造函数注入:

public class CustomFilter implements Filter {
  private final Cache<String, ClientRequest> cache;

  public CustomFilter(Cache<String, ClientRequest> cache) {
    this.cache = Objects.requireNonNull(cache);
  }

这样您就可以在单元测试中模拟缓存。这将允许单独测试CustomFilter业务逻辑,而不必处理缓存的复杂性。

之后,您可能需要对缓存配置进行单独测试,例如通过使用属性来定义到期超时。


推荐阅读