Testing

Cached results carry over between calls, which can hide behaviour in tests. Switch caching off with a property, or keep it on and check the cache through the CacheManager bean. To test expiry, move a clock instead of waiting.

Why

A test that passes only because a previous test filled the cache, or fails because a result is stale, is a flaky test. Turning caching off tests the methods; keeping it on tests the caching rules. Expiry tests must not sleep: the time to live runs on a monotonic stopwatch, so you give the cache a clock you control.

Example

import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/main.test.spring.dart';

void main() {
  // The methods themselves, without caching.
  final plain = springBootTest(springApplication, properties: {'spring.cache.type': 'none'});

  // The caching rules: the second call reads the cache.
  final cached = springBootTest(springApplication);

  test('find is cached by isbn', () async {
    final books = cached.getBean<Books>();
    await books.find('978-0');
    expect(cached.getBean<CacheManager>().getCache('books')!.get('978-0'), isNotNull);
  });
}

Expiry

A clock given to InMemoryCache or InMemoryCacheManager moves expiry forward: an entry expires once its time to live has passed on the stopwatch or on the clock.

var now = DateTime.utc(2026);
final cache = InMemoryCache(
  'books',
  spec: const CacheSpec(timeToLive: Duration(minutes: 10)),
  clock: () => now,
);
cache.put('978-0', book);
now = now.add(const Duration(minutes: 9));
expect(cache.get('978-0')?.value, book);
now = now.add(const Duration(minutes: 1)); // the whole time to live
expect(cache.get('978-0'), isNull);
fakeAsync((async) {
  final cache = InMemoryCache(
    'books',
    spec: const CacheSpec(timeToLive: Duration(minutes: 10)),
    clock: () => clock.now(),
  );
  cache.put('978-0', book);
  async.elapse(const Duration(minutes: 10));
  expect(cache.get('978-0'), isNull);
});

In Spring (Java)

@SpringBootTest(properties = "spring.cache.type=none")
class BooksTest { ... }

The same property. Spring's ConcurrentMapCacheManager has no expiry to test; with Caffeine, a Ticker plays the part of the clock.

See also