I want each integration test to create a unique database filename and delete it at the end of the test.
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var constr = $"DataSource={Guid.NewGuid()}.db";
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite(constr));
var app = builder.Build();
app.Run();
public record Person(int Id);
public class AppDbContext(DbContextOptions<AppDbContext> o) : DbContext(o)
{
public DbSet<Person> People { get; set; }
}
public interface IWebApiMarker;
In order to ease switching between DisposeAsync()
and Dispose()
, I created a compilation variable SYNC
.
#define SYNC
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
namespace WebApi.Test;
public class Test_1 : BaseTest
{
[Fact] public async Task Test() => await Task.Delay(2000);
}
#if SYNC
public abstract class BaseTest : IDisposable
#else
public abstract class BaseTest : IAsyncDisposable
#endif
{
private readonly WebApplicationFactory<IWebApiMarker> _factory;
protected BaseTest()
{
_factory = new WebApplicationFactory<IWebApiMarker>();
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureCreated();
}
#if SYNC
public void Dispose()
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureDeleted();
_factory.Dispose();
}
#else
public async ValueTask DisposeAsync()
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.EnsureDeleted();
await _factory.DisposeAsync();
}
#endif
}
I don’t understand why DisposeAsync()
fails to delete the database file at the end of each test.