Пример #1
0
        public void TestCacheExceptions()
        {
            var enumCache = new LazyStaticInMemoryCache <Type, ILookup <Enum, string> >();

            var attempts = 5;
            int runCount = 0, attemptCount = 0;

            ILookup <Enum, string> cachedEnumDescriptions = null;

            for (var x = 0; x < attempts; x++)
            {
                attemptCount++;
                try
                {
                    cachedEnumDescriptions = enumCache.GetOrAdd(typeof(StarWarsEnum), (t) =>
                    {
                        runCount++;
                        throw new Exception("Intentionally fail within the value factory...");
                    });
                }
                catch
                {
                    //DO NOTHING!
                }
            }

            Assert.IsNull(cachedEnumDescriptions);
            Assert.AreEqual(attempts, attemptCount);
            //When exceptions are thrown then the value should never be cached so execution count should match the number of attempts!
            Assert.AreEqual(attempts, runCount);
        }
Пример #2
0
        public void TestCacheLoadingAndHits()
        {
            var enumCache = new LazyStaticInMemoryCache <Type, ILookup <Enum, string> >();

            var attempts = 5;
            int runCount = 0, attemptCount = 0;

            ILookup <Enum, string> cachedEnumDescriptions = null;

            for (var x = 0; x < attempts; x++)
            {
                attemptCount++;
                cachedEnumDescriptions = enumCache.GetOrAdd(typeof(StarWarsEnum), (t) =>
                {
                    runCount++;
                    var enumDescriptionLookup = GetEnumDescriptionsLookup <StarWarsEnum>();

                    return(enumDescriptionLookup);
                });
            }

            Assert.IsNotNull(cachedEnumDescriptions);
            Assert.AreEqual(attempts, attemptCount);
            Assert.AreEqual(1, runCount);

            Assert.AreEqual("Anakin Skywalker", cachedEnumDescriptions[StarWarsEnum.DarthVader].FirstOrDefault());
            Assert.AreEqual("Luke Skywalker", cachedEnumDescriptions[StarWarsEnum.LukeSkywalker].FirstOrDefault());
            Assert.AreEqual("Obi-Wan Kenobi", cachedEnumDescriptions[StarWarsEnum.ObiWanKenobi].FirstOrDefault());
            Assert.AreEqual("R2-D2", cachedEnumDescriptions[StarWarsEnum.R2D2].FirstOrDefault());
            Assert.AreEqual("C-3PO", cachedEnumDescriptions[StarWarsEnum.C3PO].FirstOrDefault());
        }