【发布时间】:2018-03-09 14:11:41
【问题描述】:
我正在为我的 asp.net Web API 应用程序编写单元测试,其中一个正在尝试验证 AddOrGetExisting 是否正常工作。根据 MSDN 文档,AddOrGetExisting 如果已保存,则返回一个项目,否则应将其写入缓存。
我遇到的问题是,如果我从单元测试中将键添加到 MemoryCache 对象,然后调用 AddOrGetExisting,它将始终返回 null 并覆盖该值,而不是返回已保存的值。在调用 AddOrGetExisting(bool isIn 计算结果为 true)之前,我正在验证该值是否在缓存中。
这是我的内存缓存的代码和测试方法。任何帮助将不胜感激:
public static class RequestCache
{
public static TEntity GetFromCache<TEntity>(string key, Func<TEntity> valueFactory) where TEntity : class
{
ObjectCache cache = MemoryCache.Default;
var newValue = new Lazy<TEntity>(valueFactory);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
bool isIn = cache.Contains(key);
// Returns existing item or adds the new value if it doesn't exist
var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<TEntity>;
return (value ?? newValue).Value;
}
}
public string TestGetFromCache_Helper()
{
return "Test3and4Values";
}
[TestMethod]
public void TestGetFromCache_ShouldGetItem()
{
ObjectCache cache = MemoryCache.Default;
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
var cacheKey = "Test3";
var expectedValue = "Test3Value";
cache.AddOrGetExisting(cacheKey, expectedValue, policy);
var result = Models.RequestCache.GetFromCache(cacheKey,
() =>
{
return TestGetFromCache_Helper();
});
Assert.AreEqual(expectedValue, result);
}
【问题讨论】:
标签: asp.net .net caching asp.net-web-api2 memorycache