当前位置:首页 > 在Spring中快速使用EHCache注解
8. }
为了使测试简单一些我们需要使用了两个依赖:Spring Test 和Mockito:
1.
2.
3.
6.
9.
13.
测试类将依托于SpringJUnit4ClassRunner运行:
1. @RunWith(SpringJUnit4ClassRunner.class)
2. @ContextConfiguration(locations = { \ }) 3. public class CachingTest { 4. @Autowired
5. ApplicationContext context; 6. @Autowired
7. CacheManager cacheManager; 8. MessageStorage storage;
9. MessageStorage storageDelegate; 10. MessageController controller; 11. @Before
12. public void before() throws Exception {
13. storageDelegate = Mockito.mock(MessageStorage.class);
14. storage = (MessageStorage) context.getBean(\); 15. storage.setDelegate(storageDelegate);
16. controller = new MessageController(storage);
17. cacheManager.clearAll(); 18. }
19. @Test
20. public void testCaching_MessagesCache() { 21. controller.getAllMessages(); 22. controller.getAllMessages();
23. verify(storageDelegate, times(1)).findAllMessages(); 24. }
25. @Test
26. public void testCaching_MessagesCacheRemove() { 27. controller.getAllMessages(); 28. controller.getAllMessages();
29. controller.addMessage(new Message()); 30. controller.getAllMessages();
31. verify(storageDelegate, times(2)).findAllMessages();
32. verify(storageDelegate, times(1)).addMessage(any(Message.class)); 33. }
34. @Test
35. public void testCaching_MessageCache() { 36. controller.getMessageById(1); 37. controller.getMessageById(1);
38. controller.addMessage(new Message()); 39. controller.getMessageById(1);
40. verify(storageDelegate, times(1)).findMessage(1);
41. verify(storageDelegate, times(1)).addMessage(any(Message.class)); 42. } 43.}
本示例是一个模拟的对象用于测试实际的MessageStorage上的调用次数。本测试Spring上下文的配置如下:
1.
2. 3. xmlns:context=\ xmlns:ehcache=\ng-annotations.googlecode.com/svn/schema/ehcache-spring\ 4. xsi:schemaLocation=\://.springframework.org/schema/beans/spring-beans-3.0.xsd 5. ://.springframework.org/schema/context ://.springframework.org/schema/context/spring-context-3.0.xsd 6. ://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring ://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd\> 7. 8. 9. 11. 12. 14.
现在我们准备运行创建好的测试用例去验证实际在MemoryMessageStorage上的调用。我们期待的结果是:
总结
使用Ehcache Spring Annotations是很简洁的,通过上述简单的一些步骤我们试图介绍如何在您的应用中使用缓存,我强烈建议您在您的项目中使用本工具之前先去我们的网站上去读一下文档,这样您会了解一些这篇文章没有覆盖到的用法。
共分享92篇相关文档