Esempio n. 1
0
        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 );
        }
Esempio n. 2
0
        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 );
        }