1

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,

Parameswar
  • 1,951
  • 9
  • 34
  • 57

1 Answers1

1

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • thanks, this should work, but while i integrate the controller using mockMvc, can we force the filter to use this ? why i am asking is, for uni testing i can add a mock cache, but integration test use mockMvc with just the path.. i can ask this as a seperate question too. – Parameswar Nov 08 '18 at 19:52
  • If you are using Spring Boot you can create `@WebMvcTes` with `@MockBean @Primary Cache, ?> mockCache;` and it should work. Standard auto-wireing rules apply. – Karol Dowbecki Nov 08 '18 at 19:54
  • but i am not using spring boot's cache, using cache2k, will that work ? – Parameswar Nov 08 '18 at 19:54
  • It's standard bean `@Autowire` order and overrides logic, which cache you are using it makes no difference as it's based on names and types. – Karol Dowbecki Nov 08 '18 at 19:57