-
Notifications
You must be signed in to change notification settings - Fork 2
/
UnitTestBase.cs
57 lines (50 loc) · 1.84 KB
/
UnitTestBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using MccSoft.IntegreSql.EF;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using Microsoft.EntityFrameworkCore;
namespace ExampleWeb.UnitTests;
public class UnitTestBase : IDisposable
{
protected readonly IDatabaseInitializer? _databaseInitializer;
private DbContextOptions<ExampleDbContext>? _dbContextOptions;
public UnitTestBase(
DatabaseType? databaseType,
DatabaseSeedingOptions<ExampleDbContext>? seedingOptions = null
)
{
_databaseInitializer = CreateDatabaseInitializer(databaseType);
_dbContextOptions = _databaseInitializer
?.CreateDatabaseGetDbContextOptionsBuilderSync<ExampleDbContext>(
seedingOptions: seedingOptions
)
?.Options;
}
private IDatabaseInitializer? CreateDatabaseInitializer(DatabaseType? databaseType)
{
return databaseType switch
{
null => null,
DatabaseType.Postgres
=> new NpgsqlDatabaseInitializer(
// This is needed if you run tests NOT inside the container.
// 5434 is the public port number of Postgresql instance
connectionStringOverride: new() { Host = "localhost", Port = 5434 }
)
{
DropDatabaseOnRemove = true,
},
DatabaseType.Sqlite => new SqliteDatabaseInitializer(),
_ => throw new ArgumentOutOfRangeException(nameof(databaseType), databaseType, null)
};
}
public ExampleDbContext CreateDbContext()
{
if (_dbContextOptions == null)
return null!;
return new ExampleDbContext(_dbContextOptions);
}
public void Dispose()
{
_databaseInitializer?.RemoveDatabase(CreateDbContext().Database.GetConnectionString());
}
}