Cache { public T get(String key, CacheableData<T> cacheableData) { if (value.get(key) != null) { return value.get(key); } T fetchedData = cacheableData.fetch(); value.put(key, fetchedData); return fetchedData; } Cache(); T get(String key, CacheableData<T> cacheableData);  }
@Test public void shouldGetAndCacheValueOnlyWhenItDoesNotExist() throws Exception { Cache<String> cache = new Cache<String>(); when(cacheableData.fetch()).thenReturn("value"); assertEquals("value", cache.get("key", cacheableData)); verify(cacheableData).fetch(); assertEquals("value", cache.get("key", cacheableData)); verify(cacheableData, times(1)).fetch(); }
@Test public void shouldClearCacheWhenActionsAreUpdated() throws Exception { Cache<String> cache = new Cache<String>(); when(cacheableData.fetch()).thenReturn("value"); cache.get("key", cacheableData); Event.ON_DATA_FETCHED.notifyListeners(fetched); assertEquals("value", cache.get("key", cacheableData)); verify(cacheableData, times(2)).fetch(); Event.ON_DATA_FETCHED.notifyListeners(fetchedFailed); assertEquals("value", cache.get("key", cacheableData)); verify(cacheableData, times(2)).fetch(); }
@Test public void shouldClearCacheWhenFormIsSubmitted() throws Exception { Cache<String> cache = new Cache<String>(); when(cacheableData.fetch()).thenReturn("value"); cache.get("key", cacheableData); Event.FORM_SUBMITTED.notifyListeners("ec_registration"); assertEquals("value", cache.get("key", cacheableData)); verify(cacheableData, times(2)).fetch(); }