Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用cache2k对过滤器进行单元测试_Java_Unit Testing_Cache2k - Fatal编程技术网

Java 如何使用cache2k对过滤器进行单元测试

Java 如何使用cache2k对过滤器进行单元测试,java,unit-testing,cache2k,Java,Unit Testing,Cache2k,我有一个使用缓存的servlet过滤器,代码基本上是这样的 public class CustomFilter implements Filter { private final Cache<String, ClientRequest> cache; @Autowired public CustomFilter(Service service){ cache = Caching.getCachingProvider().getCacheManager

我有一个使用缓存的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)));
    }
}
公共类CustomFilter实现过滤器{
私有最终缓存;
@自动连线
公共客户过滤器(服务){
cache=Caching.getCachingProvider().getCacheManager()
.createCache(“requestsCache”,
ExtendedMutableConfiguration.of(
Cache2kBuilder.of(String.class,
ClientRequest.class).入口容量(100)
.expireAfterWrite(1000,时间单位为秒));
}
}
关于如何在此过滤器中使用此类的单元测试方法,有何想法?提前感谢,

缓存
创建提取到外部配置,并通过过滤器构造函数注入:

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

  public CustomFilter(Cache<String, ClientRequest> cache) {
    this.cache = Objects.requireNonNull(cache);
  }
公共类CustomFilter实现过滤器{
私有最终缓存;
公共自定义筛选器(缓存){
this.cache=Objects.requirennull(缓存);
}
这样,您可以在单元测试中模拟缓存。这将允许单独测试
CustomFilter
业务逻辑,而不必处理缓存的复杂性


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

谢谢,这应该可以工作,但是当我使用mockMvc集成控制器时,我们可以强制过滤器使用它吗?我问的原因是,对于uni测试,我可以添加一个模拟缓存,但是集成测试使用mockMvc,只需e path..我也可以单独问这个问题。如果你使用Spring Boot,你可以用
@MockBean@Primary Cache mockCache;
创建
@WebMvcTes
,它应该可以工作。标准的自动连线规则适用。但我没有使用Spring Boot的缓存,而是使用cache2k,这会工作吗?这是标准的bean
@Autowire
命令和命令重写逻辑,因为它基于名称和类型,所以您正在使用的缓存没有任何区别。