使用MemoryCache UpdateCallback进行测试

时间:2014-12-04 04:37:08

标签: c# asp.net unit-testing caching memorycache

以下测试间歇性失败。它在MemoryCache中缓存一个具有绝对过期时间的项目,以及在删除项目之前应该调用的更新回调。但是,有时候在测试结束之前会调用回调,有时根本不会。

如果缓冲时间足够长,则至少会调用一次。但这并不符合我的目的,因为我要求缓存总是在数据过期之前尝试更新数据。

现在在我的真实场景中,我不会有10秒的到期时间和粒度,但是这个测试间歇性地失败仍然让我感到困扰。

有人想过为什么会这样吗?

注意:间歇性失败,60秒到期,5秒缓冲。

using System;
using System.Runtime.Caching;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MemoryCacheTest
{
    private const double ExpiryInSeconds = 10;
    private const double ExpiryBufferInSeconds = 5;

    private readonly object updateItemCounterLock = new object();
    private int updateItemCounter = 0;

    [TestMethod]
    public async Task MemoryCacheUpdateTest()
    {
        // Set item in cache with absolute expiration defined above
        MemoryCache cache = MemoryCache.Default;
        CacheItem cacheItem = new CacheItem("key", "value");
        CacheItemPolicy cacheItemPolicy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now + TimeSpan.FromSeconds(ExpiryInSeconds),
            UpdateCallback = new CacheEntryUpdateCallback(this.UpdateItem)
        };
        cache.Set(cacheItem, cacheItemPolicy);

        // Delay for absolute expiration time + buffer
        await Task.Delay(TimeSpan.FromSeconds(ExpiryInSeconds) + TimeSpan.FromSeconds(ExpiryBufferInSeconds));

        // Test that the update callback was invoked once
        Assert.AreEqual(1, updateItemCounter);
    }

    // Incrememnts the updateItemCounter
    private void UpdateItem(CacheEntryUpdateArguments args)
    {
        lock (updateItemCounterLock)
        {
            updateItemCounter++;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为调用新的CacheEntryUpdateCallback是多余的。你可以打电话:         UpdateCallback = new CacheEntryUpdateCallback(this.UpdateItem)而不是

答案 1 :(得分:0)

由于没有这个问题的解决方案,我将我需要的MemoryCache方法抽象到接口中并对其进行测试。那时测试变得无效,因为我刚刚测试了我自己的接口实现。