MemoryCache:为什么这个集成测试失败了? UpdateCallBack看起来好像坏了

时间:2013-07-11 14:12:47

标签: c# caching integration-testing

在一个理智的世界中,我原本期望UpdateCallBack属性增加我的参数集合。但它没有:在此测试的最后一行中,updateArguments集合预计为3(每Set次调用两次,Remove调用一次),但它是空的。

测试粗糙且准备就绪,但它应该足以说明发生了奇怪的事情。

或者我错过了一些明显的东西。

编辑:这变得越来越陌生了。根据问题MemoryCache UpdateCallback not workingThread.Sleep阻止MemoryCache.Default对象,我将原来的Thread.Sleep(5000)调用更改为Task.Factory.StartNew(() => Thread.Sleep(10000)).Wait();。然后,如果我注释掉对MemoryCache.Default.Remove()的调用,则updateArguments集合确实会增加,但只会增加一次,即"PersonKey"缓存项目到期时。完全忽略了两个Set()和一个Remove()调用。我有一个“真是太棒了”的时刻。

[Test]
public void TheMemoryCacheMaintainsAMemberAndInvokesTheUpdateCallback()
{
    var person = new Person { GivenName = "Rob", LastName = "Lyndon"};
    var givenName = person.GivenName;
    var lastName = person.LastName;

    var updateArguments = new List<CacheEntryUpdateArguments>();

    MemoryCache.Default.Set("PersonKey", person, CreateNewPolicy(updateArguments));
    var cachedItem = MemoryCache.Default.Get("PersonKey") as Person;
    Assert.IsNotNull(cachedItem);
    Assert.That(cachedItem.GivenName, Is.EqualTo(givenName));
    Assert.That(cachedItem.LastName, Is.EqualTo(lastName));

    person.LastName = "Lyndon - Updated";
    MemoryCache.Default.Set("PersonKey", member, CreateNewPolicy(updateArguments));
    cachedItem = MemoryCache.Default.Get("PersonKey") as Person;
    Assert.IsNotNull(cachedItem);
    Assert.That(cachedItem.GivenName, Is.EqualTo(givenName));
    Assert.That(cachedItem.LastName, Is.EqualTo(lastName + " - Updated"));

    Task.Factory.StartNew(() => Thread.Sleep(10000)).Wait();
    Thread.Sleep(5000);
    Assert.That(updateArguments.Count, Is.EqualTo(3));
}

private static CacheItemPolicy CreateNewPolicy(ICollection<CacheEntryUpdateArguments> updateArguments)
{
    return new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1),
            UpdateCallback = args => updateArguments.Add(args)
        };
}

0 个答案:

没有答案