gpt4 book ai didi

c# - 在单元测试中模拟 IMemoryCache

转载 作者:可可西里 更新时间:2023-11-01 07:56:04 26 4
gpt4 key购买 nike

我正在使用 asp net core 1.0 和 xunit。

我正在尝试为一些使用 IMemoryCache 的代码编写单元测试。但是,每当我尝试在 IMemoryCache 中设置一个值时,我都会收到 Null 引用错误。

我的单元测试代码是这样的:
IMemoryCache 被注入(inject)到我要测试的类中。但是,当我尝试在测试中的缓存中设置一个值时,我得到了一个空引用。

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
}

这是类测试...

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 时,默认值是什么?

最佳答案

IMemoryCache.Set 是一种扩展方法,因此不能使用 Moq 进行模拟框架。

扩展代码可用 here

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 中,它还会调用缓存条目上的扩展方法,因此也必须满足这一点。这会很快变得复杂,所以我建议使用具体的实现

//...
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
//...
}

现在您可以访问功能齐全的内存缓存。

关于c# - 在单元测试中模拟 IMemoryCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com