使用 azure redis 进行单元测试和 IDistributedCache

use*_*078 3 c# unit-testing .net-core

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

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

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

    public CacheManager(IDataManager dataservices, IDistributedCache cache)
    {
        _cache = cache;
        _dataservices = dataservices;
    }
Run Code Online (Sandbox Code Playgroud)

startup.cs 中的代码使用了 ConfigureServices

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

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

Sau*_*001 6

我已经使用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
        }

Run Code Online (Sandbox Code Playgroud)

在我的示例中,我在 .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" />

Run Code Online (Sandbox Code Playgroud)


Nko*_*osi 3

您可以模拟接口,使其按照隔离单元测试的需要运行。

public void Test_CacheManager() {
    //Arrange
    IDataManager dataservices = new Mock<IDataManager>(); 
    IDistributedCache cache = new Mock<IDistributedCache>();
    var subject = new CacheManager(dataservices.Object, cache.Object);

    //Setup the mocks to behave as expected.

    //Act
    //...call the method under test

    //Assert
    //...assert the expected behavior
}
Run Code Online (Sandbox Code Playgroud)

上面的示例使用 Moq 来演示如何模拟被测类的依赖项的实例。

请参考Moq 快速入门以更好地了解如何使用模拟库。

如果您要连接到实际的 Redis 连接,那么这将不再是单元测试,而是集成测试,这将需要完全不同的方法。

public void Test_CacheManager() {
    //Arrange

    IDataManager dataservices = new Mock<IDataManager>(); 
     //Setup the mocks to behave as expected.

    //Configure Redis Cache
    var services = new ServiceCollection();
    var redisconnection = "...";
    services.AddDistributedRedisCache(o => { o.Configuration = redisconnection; });
    var provider = services.BuildServiceProvider();
    IDistributedCache cache = provider.GetService<IDistributedCache>();

    var subject = new CacheManager(dataservices.Object, cache);

    //Act
    //...call the method under test

    //Assert
    //...assert the expected behavior
}
Run Code Online (Sandbox Code Playgroud)