【发布时间】:2021-07-26 14:23:33
【问题描述】:
我创建了一些基本的集成测试来调用我的 Api 并查看权限是否正常工作。现在我遇到了一个问题,即运行更多的所有测试其中一个失败 - 如果单独运行,它不会。
原因是,一旦用户登录,我就使用 IMemoryCache 来存储某些权限。但是对于我的集成测试,权限存储在缓存中,当我尝试更改它们以进行测试时,它们不会刷新.
一般来说,有没有办法让每个集成测试的 MemoryCache 失效?
我的一个集成测试类基本上是这样做的:
public IntegrationTest(CustomWebApplicationFactory<Namespace.Startup> factory)
{
_factory = factory;
_client = _factory.CreateClient();
// init the DB here etc...
var response = await _client.GetAsync("api/Some/Path");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
有没有办法告诉工厂不要使用缓存或使用模拟缓存或类似的东西?
编辑:
缓存在我的 startup.cs 中设置如下:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
[...]
}
}
这通过 DependenyInjection 注入到我的控制器中,如下所示:
private IMemoryCache _cache;
private MemoryCacheEntryOptions _cacheOptions;
const int CACHE_LIFETIME_IN_DAYS = 7;
public SomeController(IMemoryCache cache) {
_cache = cache;
_cacheOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(CACHE_LIFETIME_IN_DAYS));
}
我在我的控制器中使用它与_cache.TryGetValue 和_cache.Set
【问题讨论】:
-
你能说明一下缓存是在哪里以及如何设置和使用的吗?
-
好的,我编辑了最初的问题,其中包含有关如何设置缓存的信息。谢谢!
标签: c# .net-core integration-testing