Inject memory cache into the tests

If we try to execute unit tests using RedisCacheFilter, we will notice that get_by_id_should_return_right_data will fail. This is because the Redis instance is not available in the development environment. Furthermore, we can use the MemoryDistributedCache implementation to perform our tests. The MemoryDistributedCache implementation is done in the same class that's used by the AddDistributedMemoryCache extension method. As we mentioned in the previous chapter, the class doesn't provide a real distributed cache, and it is used for testing purposes.

For that reason, we can add the following line to the InMemoryApplicationFactory<TStartup> class, which is contained in the Catalog.Fixtures project:

namespace Catalog.Fixtures
{
public class InMemoryApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder
builder)
{
builder.UseEnvironment("Testing")
.ConfigureTestServices(services =>
{
...
services.AddSingleton<IDistributedCache,
MemoryDistributedCache>();

...
});
}
}
}

The preceding code replaces the implementation of IDistributedCache with an instance of MemoryDistributedCache. Therefore, every time our implementation calls the IDistributedCache interface, the data is saved in the memory of the testing server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.211.66