Unit testing ehcache (Take #2)
My solution works, but there was something smelly in there. I wasn’t satisfied with the way I was checking to ensure that the cache had actually been accessed. Given that the notification interface doesn’t define a method to find that out, I had sort of tricked it ….
Well, I obviously couldn’t leave it at that. So the solution to a better smelling cache unit test lies below (tip: use the Statistics information that’s right there on the cache, but I hadn’t noticed)
import junit.framework.Assert;
@Test
public void testCache() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
DataFacade dataFacade = (DataFacade) context.getBean("cacheInjectedDataFacade");
TestCacheListener listener = new TestCacheListener();
Cache cache = dataFacade.getCache();
cache.getCacheEventNotificationService().registerListener(listener);
dataFacade.getData();
Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
Assert.assertNotNull(cache.get(DataFacade.CACHE_KEY));
listener.resetLastStatus();
Assert.assertEquals(listener.getLastStatus(), ListenerStatus.RESET);
dataFacade.getData();
Assert.assertEquals(1, cache.getStatistics().getCacheHits());
Thread.sleep(2500);
dataFacade.getData();
Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
}
Also, remember to reset your cache through cache.removeAll() between tests (through the @BeforeTest) or else your cache hits won’t jive.
| Print article |