gpt4 book ai didi

c# - 使用 azure redis 的单元测试和 IDistributedCache

转载 作者:行者123 更新时间:2023-11-30 22:59:15 26 4
gpt4 key购买 nike

我有一个 Azure Redis 和 .Net Core 2 的工作实现,使用的代码与此 article 中描述的非常相似

我的问题是,如何从单元测试类实例化缓存实例?我查看了许多资源,但一无所获。

我需要能够创建一个实例来实例化一个类,例如

    public CacheManager(IDataManager dataservices, IDistributedCache cache)
{
_cache = cache;
_dataservices = dataservices;
}

startup.cs中的代码使用了ConfigureServices

            //Configure Redis Cache
var redisconnection = Configuration.GetConnectionString("Redis");
services.AddDistributedRedisCache(o => { o.Configuration = redisconnection; });

也许我需要在单元测试项目中添加一个包?这是怎么做到的?

最佳答案

我使用 Microsoft.Extensions.Caching.Distributed.MemoryDistributedCache 类进行单元测试。这是 IDistributedCache 的内存中实现。

这是我的单元测试代码片段。

        [TestMethod]
public void ExampleTestMethod()
{
var expectedData = new byte[] { 100, 200 };

var opts = Options.Create<MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions());
IDistributedCache cache1 = new MemoryDistributedCache(opts);
cache1.Set("key1", expectedData);
var cachedData = cache1.Get("key1");

Assert.AreEqual(expectedData, cachedData);

//Use the variable cache as an input to any class which expects IDistributedCache
}

在我的示例中,我使用的是 .NET Core 3.1,相关的 NUGET 包是

    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="3.1.4" />

关于c# - 使用 azure redis 的单元测试和 IDistributedCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335487/

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