Skip to content

Instantly share code, notes, and snippets.

@bijukunjummen
Created August 10, 2012 16:08
Show Gist options
  • Save bijukunjummen/3315275 to your computer and use it in GitHub Desktop.
Save bijukunjummen/3315275 to your computer and use it in GitHub Desktop.
Test Cache with Spring Cache Abstraction
package org.bk.samples.cache;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestSpringCache.TestConfiguration.class})
public class TestSpringCache {
@Autowired TestService testService;
@Test
public void testCache() {
String response1 = testService.cachedMethod("param1", "param2");
String response2 = testService.cachedMethod("param1", "param2");
assertThat(response2, equalTo(response1));
}
@Configuration
@EnableCaching
@ComponentScan("org.bk.samples.cache")
public static class TestConfiguration{
@Bean
public SimpleCacheManager cacheManager(){
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<Cache> caches = new ArrayList<Cache>();
caches.add(cacheBean().getObject());
cacheManager.setCaches(caches );
return cacheManager;
}
@Bean
public ConcurrentMapCacheFactoryBean cacheBean(){
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
cacheFactoryBean.setName("default");
return cacheFactoryBean;
}
}
}
interface TestService{
String cachedMethod(String param1,String param2);
}
@Component
class TestServiceImpl implements TestService{
@Cacheable(value="default", key="#p0.concat('-').concat(#p1)")
public String cachedMethod(String param1, String param2){
return "response " + new Random().nextInt();
}
}
@meghadureja
Copy link

Thank You!

@angstream555
Copy link

You are a lifesaver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment