public void TestInit() { _mockCacheProvider = Substitute.For <ICacheProvider>(); _manager = new DefaultCacheManager(_mockCacheProvider, new DefaultCacheKey()); _mockRepository = Substitute.For <ITest3Repository>(); _key = "a"; _cacheKey = "CacheKey_a"; _signKey = "CacheKey_Sign_a"; _testA = Test3.CreateA(); }
private static void PlainExample() { Console.WriteLine("PlainExample"); var cacheHolder = new ConcurrentDictionaryCacheHolder(); var cacheFactory = new ActivatorCacheFactory(); var cacheManager = new DefaultCacheManager(cacheHolder, cacheFactory); var reportService = new ReportService(); var cachedReportService = new CachedReportService(cacheManager, reportService); var report = cachedReportService.GetReport(); var report2 = cachedReportService.GetReport(); Console.WriteLine("Reports are equal? : {0}", report == report2); Console.WriteLine(); }
public void TestGet_Concurrency() { //设置仓储操作 _mockRepository.GetTest3().Returns(_testA); //设置仅当调用了添加缓存方法后,才能获取 _mockCacheProvider.When(t => t.Add(_cacheKey, _testA, 20)) .Do(invocation => _mockCacheProvider.Get <Test3>(_cacheKey).Returns(_testA)); _mockCacheProvider.When(t => t.Add(_signKey, "a", 10)) .Do(invocation => _mockCacheProvider.Get <string>(_signKey).Returns("a")); //并发读取缓存 UnitTest.TestConcurrency(() => { var manager = new DefaultCacheManager(_mockCacheProvider, new DefaultCacheKey()); manager.Get(_key, () => _mockRepository.GetTest3(), 10); }, 5); //验证仓储只被调用一次,说明同时只有一个线程能更新缓存 _mockRepository.Received(1).GetTest3(); //验证缓存只被添加一次 _mockCacheProvider.Received(1).Add(_cacheKey, _testA, 20); }
public void TestGet_Concurrency2() { //模拟已加载缓存 _mockCacheProvider.Get <Test3>(_cacheKey).Returns(_testA); //模拟缓存过期标记已到期 _mockCacheProvider.Get <string>(_signKey).Returns(""); //添加缓存过期标记后,返回"a" _mockCacheProvider.When(t => t.Add(_signKey, "a", 10)) .Do(invocation => _mockCacheProvider.Get <string>(_signKey).Returns("a")); //并发读取缓存 UnitTest.TestConcurrency(() => { var manager = new DefaultCacheManager(_mockCacheProvider, new DefaultCacheKey()); manager.Get(_key, () => _mockRepository.GetTest3(), 10); }, 5); //验证添加缓存过期标记1次 _mockCacheProvider.Received(1).Add(_signKey, "a", 10); //验证不会调用添加缓存 _mockCacheProvider.DidNotReceive().Add(_cacheKey, _testA, 20); //验证缓存在过期时被更新 _mockCacheProvider.Received(1).Update(_cacheKey, Arg.Any <object>(), 20); }
public ProjectInterfaceService(IMyProjectService myProjectService, ICacheManager cacheManager) { _myProjectService = myProjectService; _cacheManager = (DefaultCacheManager)cacheManager; }