|
7 | 7 | public class DatabaseTestFixture : IAsyncLifetime |
8 | 8 | { |
9 | 9 | private PostgreSqlContainer? _postgresContainer; |
10 | | - private TestDbContext? _dbContext; |
11 | | - |
12 | | - public TestDbContext DbContext => _dbContext ?? throw new InvalidOperationException("Database not initialized"); |
| 10 | + public TestDbContext DbContext { get; set; } = null!; |
13 | 11 |
|
14 | 12 | public async Task InitializeAsync() |
15 | 13 | { |
16 | | - // Create and start PostgreSQL container |
17 | 14 | _postgresContainer = new PostgreSqlBuilder() |
18 | | - .WithImage("postgres:16-alpine") |
19 | | - .WithDatabase("testdb") |
20 | | - .WithUsername("test") |
21 | | - .WithPassword("test") |
| 15 | + .WithImage("postgres:18-alpine") |
22 | 16 | .Build(); |
23 | 17 |
|
24 | 18 | await _postgresContainer.StartAsync(); |
25 | 19 |
|
26 | | - // Create DbContext with connection to container |
27 | 20 | var connectionString = _postgresContainer.GetConnectionString(); |
28 | 21 | var optionsBuilder = new DbContextOptionsBuilder<TestDbContext>(); |
29 | 22 | optionsBuilder.UseNpgsql(connectionString); |
30 | 23 |
|
31 | | - // Enable EF Core logging |
32 | | - optionsBuilder.LogTo( |
33 | | - Console.WriteLine, |
34 | | - new[] { DbLoggerCategory.Database.Command.Name, DbLoggerCategory.Query.Name }, |
35 | | - LogLevel.Information, |
36 | | - DbContextLoggerOptions.DefaultWithLocalTime | DbContextLoggerOptions.SingleLine |
37 | | - ); |
38 | | - |
39 | | - optionsBuilder.EnableSensitiveDataLogging(); |
40 | | - optionsBuilder.EnableDetailedErrors(); |
| 24 | + DbContext = new TestDbContext(optionsBuilder.Options); |
41 | 25 |
|
42 | | - _dbContext = new TestDbContext(optionsBuilder.Options); |
| 26 | + await DbContext.Database.EnsureCreatedAsync(); |
43 | 27 |
|
44 | | - // Create database schema |
45 | | - await _dbContext.Database.EnsureCreatedAsync(); |
46 | | - |
47 | | - // Seed test data |
48 | 28 | await SeedTestData(); |
49 | 29 | } |
50 | 30 |
|
51 | 31 | private async Task SeedTestData() |
52 | 32 | { |
53 | 33 | var users = TestData.Users.Values.ToList(); |
54 | | - await _dbContext.Users.AddRangeAsync(users); |
55 | | - await _dbContext.SaveChangesAsync(); |
| 34 | + |
| 35 | + await DbContext.Users.AddRangeAsync(users); |
| 36 | + await DbContext.SaveChangesAsync(); |
56 | 37 | } |
57 | 38 |
|
58 | 39 | public async Task DisposeAsync() |
59 | 40 | { |
60 | | - if (_dbContext != null) |
| 41 | + if (DbContext != null) |
61 | 42 | { |
62 | | - await _dbContext.DisposeAsync(); |
| 43 | + await DbContext.DisposeAsync(); |
63 | 44 | } |
64 | 45 |
|
65 | 46 | if (_postgresContainer != null) |
|
0 commit comments