Skip to content

Testing

Ben Manes edited this page Aug 25, 2018 · 3 revisions
FakeTicker ticker = new FakeTicker(); // Guava's testlib
Cache<Key, Graph> cache = Caffeine.newBuilder()
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .executor(Runnable::run)
    .ticker(ticker::read)
    .maximumSize(10)
    .build();

cache.put(key, graph);
ticker.advance(30, TimeUnit.MINUTES)
assertThat(cache.getIfPresent(key), is(nullValue()));

Testing timed eviction does not require that tests wait until the wall clock time has elapsed. Use the Ticker interface and the Caffeine.ticker(Ticker) method to specify a time source in your cache builder, rather than having to wait for the system clock. Guava's testlib provides a convenient FakeTicker for this purpose. As the removal of expired entries is performed during a maintenance cycle, use Cache.cleanUp() to trigger one immediately when tests depend on eviction having occurred.

Caffeine delegates periodic maintenance, removal notifications, and asynchronous computations to an Executor. This provides more predictable response times by not penalizing the caller and uses ForkJoinPool.commonPool() by default. Use the Caffeine.executor(Executor) method to specify a direct (same thread) executor in your cache builder, rather than having to wait for the asynchronous tasks to complete.

We recommend Awaitility for multi-threaded testing.

Clone this wiki locally