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

标签 c# unit-testing .net-core

我有一个 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/

相关文章:

C# 更正来自 C++ 的托管代码

c# - NUnit 测试用例预期消息

visual-studio-2015 - Dot net core 1 Tooling Preview 离线安装器

php - 如何在不为每个函数运行新的浏览器窗口的情况下运行 PHPUnit Selenium 测试?

perl - 我怎样才能在 Perl 发行版中只运行特定的测试?

c# - 在 Startup.cs 之外实现依赖注入(inject)

c# - 在 linux 机器上运行 c# 应用程序时 SOAP 身份验证失败

c# - 通用约束忽略协方差

c# - 我的打印 PDF 不显示原始窗口的绑定(bind)数据 - C# MVVM

ruby - 在 RSpec instance_double 上 stub 一个 setter