I have below test class, Where I am defining _cacheExecutor dictionary at class level, and the purpose is mainly to cache the results with type T and test data as keys.
public class CodesAndGuidelinesTest : SchemaCache, IClassFixture<PostgreSqlResource>
{
private readonly Dictionary<(Type, object), Task<IRequestExecutor>> _cacheExecutor = new();
public CodesAndGuidelinesTest(PostgreSqlResource resource) :base(resource) { }
[Fact]
public async Task Create_Name_Contains_Expression()
{
IRequestExecutor requestExecutor = await CreateSchemaAsync(CodesAndGuidelinesMockFixture.codeStandardGuidelines, _cacheExecutor);
.......
.......
}
[Fact]
public async Task Create_Name_NotContains_Expression()
{
IRequestExecutor requestExecutor = await CreateSchemaAsync(CodesAndGuidelinesMockFixture.codeStandardGuidelines, _cacheExecutor);
.......
.......
}
}
Below is the SchemaCache class
public class SchemaCache : QueryTestBase
{
public SchemaCache(PostgreSqlResource resouce) : base(resouce) { }
public Task<IRequestExecutor> CreateSchemaAsync<T>(T[] entities,
Dictionary<(Type, object), Task<IRequestExecutor>> cacheExecutor) where T : class
{
(Type, T[] entites) key = (typeof(T), entities);
if (cacheExecutor.TryGetValue(key, out var result))
{
return result;
}
else // else block will always be executed when I run the test methods all at once
{
cacheExecutor[key] = CreateDb(entities);
}
return cacheExecutor[key];
}
}
In the above class, I store the test data and type combined as keys in the dictionary and the results Task<IRequestExecutor> as values.
When executing the test methods all at once, For the first test method, it goes to the createDb, and the keys and values are stored in _cacheExecutor, and for the following test method _cacheExecutor has null values and thus it's going into the else block. The else block will always be executed because of the dictionary at class-level declaration, and for the new method, the _cacheExecutor will be null.
Could anyone please let me know any better solution or suggestion?
Thanks in advance!!