问题描述
我正在使用 asp net core 1.0 和 xunit.
I am using asp net core 1.0 and xunit.
我正在尝试为一些使用 IMemoryCache 的代码编写单元测试.但是,每当我尝试在 IMemoryCache 中设置一个值时,我都会收到 Null 引用错误.
I am trying to write a unit test for some code that uses IMemoryCache. However whenever I try to set a value in the IMemoryCache I get an Null reference error.
我的单元测试代码是这样的:IMemoryCache 被注入到我要测试的类中.但是,当我尝试在测试中的缓存中设置一个值时,我得到一个空引用.
My unit test code is like this:
The IMemoryCache is injected into the class I want to test. However when I try to set a value in the cache in the test I get a null reference.
public Test GetSystemUnderTest()
{
var mockCache = new Mock<IMemoryCache>();
return new Test(mockCache.Object);
}
[Fact]
public void TestCache()
{
var sut = GetSystemUnderTest();
sut.SetCache("key", "value"); //NULL Reference thrown here
}
这是Test类...
public class Test
{
private readonly IMemoryCache _memoryCache;
public Test(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public void SetCache(string key, string value)
{
_memoryCache.Set(key, value, new MemoryCacheEntryOptions {SlidingExpiration = TimeSpan.FromHours(1)});
}
}
我的问题是...我需要以某种方式设置 IMemoryCache 吗?为 DefaultValue 设置一个值?当 IMemoryCache 被 Mocked 时,默认值是多少?
My question is...Do I need to setup the IMemoryCache somehow? Set a value for the DefaultValue? When IMemoryCache is Mocked what is the default value?
推荐答案
IMemoryCache.Set 是扩展方法,因此无法使用 Moq 框架.
IMemoryCache.Set Is an extension method and thus cannot be mocked using Moq framework.
扩展的代码虽然可用 这里
public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)
{
using (var entry = cache.CreateEntry(key))
{
if (options != null)
{
entry.SetOptions(options);
}
entry.Value = value;
}
return value;
}
对于测试,需要通过扩展方法模拟一条安全路径,以使其顺利完成.在 Set 中,它还调用缓存条目上的扩展方法,因此也必须满足这一要求.这会很快变得复杂,所以我建议使用具体的实现
For the test, a safe path would need to be mocked through the extension method to allow it to flow to completion. Within Set it also calls extension methods on the cache entry, so that will also have to be catered for. This can get complicated very quickly so I would suggest using a concrete implementation
//...
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
//...
public Test GetSystemUnderTest() {
var services = new ServiceCollection();
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var memoryCache = serviceProvider.GetService<IMemoryCache>();
return new Test(memoryCache);
}
[Fact]
public void TestCache() {
//Arrange
var sut = GetSystemUnderTest();
//Act
sut.SetCache("key", "value");
//Assert
//...
}
所以现在您可以访问功能齐全的内存缓存了.
So now you have access to a fully functional memory cache.
这篇关于在单元测试中模拟 IMemoryCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)