Search code examples
javaunit-testingcache2k

How to unit test a filter using cache2k


i am having a servlet filter which uses cache,the code basically goes like this

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)));
    }
}

Any thoughts about how can i unit test methods in this filter which use this class ? thanks in advance,


Solution

  • Extract Cache<String, ClientRequest> creation to external configuration and inject it through filter constructor:

    public class CustomFilter implements Filter {
      private final Cache<String, ClientRequest> cache;
    
      public CustomFilter(Cache<String, ClientRequest> cache) {
        this.cache = Objects.requireNonNull(cache);
      }
    

    That way you can mock the cache in your unit tests. This will allow to test CustomFilter business logic in isolation, without having to deal with complexity of the cache.

    After that you might need a separate test for your cache configuration e.g. by using a property to define expiry timeout.