I have plagiarized the below code from the mightysoft docs site on integration testing and adapted it slightly to meet my needs:
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
private readonly SeedDataClass _seed;
public CustomWebApplicationFactory(SeedDataClass seed)
{
_seed = seed;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.UseEnvironment("Development");
builder.ConfigureServices(services =>
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
services.AddSingleton(_seed);
services.AddDbContextPool<GatewayContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
options.EnableSensitiveDataLogging();
});
var sp = services.BuildServiceProvider();
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<GatewayContext>();
var logger = scopedServices
.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();
var seed = scopedServices.GetRequiredService<SeedDataClass>();
db.Database.EnsureCreated();
try
{
seed.InitializeDbForTests(db);
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred seeding the database with test messages. Error: {ex.Message}");
}
}
});
}
}
To be used like in a test like:
_client = new CustomWebApplicationFactory<Startup>(new SeedDataClass()).CreateClient();
And this all works but I am looking to add generics to the custom web app factory class and move this code into a nuget package I am working on for internal testing work.
Something like this:
public class CustomWebApplicationFactory<TStartup, TContext>
: WebApplicationFactory<TStartup>
where TStartup : class
where TContext : DbContext
I am stuck on how to provide/inject the SeedDataClass
class instance into my new generic custom web app factory.