我使用类似于本article
中描述的代码的Azure Redis和.Net Core 2的有效实现我的问题是,如何从单元测试类实例化缓存的实例?我浏览了许多资源,却一无所获。
我需要能够创建一个实例来实例化诸如这样的类
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; });
也许我需要向单元测试项目中添加一个包?怎么做?
答案 0 :(得分:1)
您可以仅模拟接口以使其符合隔离单元测试的要求。
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
}
上面的示例使用Moq来演示如何模拟被测类的依赖项实例。
参考Moq Quickstart,以更好地了解如何使用模拟库。
如果要连接到实际的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
}
答案 1 :(得分:1)
这是我在.net core 2.0和3.1中设法做到的方法。 您需要使用MemoryDistributedCache。并通过您的服务构造函数。真实地说,您的服务通过de量注入使用IDistributedCache。 MemoryDistributedCache还实现IDistributedCache。
var mockedCacheSettings = new Mock<IOptions<CacheSettings>>();
var options = new OptionsWrapper<MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions());
_memoryDistributedCache = new MemoryDistributedCache(options);
_distributedCacheService = new DistributedCacheService(_memoryDistributedCache, mockedCacheSettings.Object, NullLogger<DistributedCacheService>.Instance);
答案 2 :(得分:1)
我已经使用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" />