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.
- Move a clock, don't wait:
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);
fake_asyncalone expires nothing.async.elapsemoves fake time, not the stopwatch. Give the cache a clock that follows fake time,() => clock.now()(packageclock, whichfakeAsyncfakes), and write and read inside the samefakeAsync. Write the closure: the tear-offclock.nowkeeps the clock of the zone it was taken in.
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);
});
- Choose a long time to live. Real time expires entries too, whatever the clock, so a time to live of a second can expire an entry the test still expects on a slow machine. Give minutes and move the clock past them. A clock set back before the write also counts as expired.
- In an application test, the
cacheManagerthe starter makes from the properties has no clock: declare your ownInMemoryCacheManagerbean with the specs and aclock(it replaces the starter's), then move that clock.
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.