-
Notifications
You must be signed in to change notification settings - Fork 2
/
UnitTestWithMigrations.cs
50 lines (44 loc) · 1.59 KB
/
UnitTestWithMigrations.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
using System;
using System.Threading.Tasks;
using MccSoft.IntegreSql.EF;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace ExampleWeb.UnitTests;
public class UnitTestWithMigrations : IDisposable
{
private readonly DbContextOptions<ExampleDbContext> _dbContextOptions;
private readonly NpgsqlDatabaseInitializer _databaseInitializer;
public UnitTestWithMigrations()
{
_databaseInitializer = 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, }
);
_dbContextOptions = _databaseInitializer
.CreateDatabaseGetDbContextOptionsBuilderSync<ExampleDbContext>(
new DatabaseSeedingOptions<ExampleDbContext>(
"DatabaseUsingMigrations",
context => context.Database.MigrateAsync(),
DisableEnsureCreated: true
)
)
.Options;
}
public ExampleDbContext CreateDbContext()
{
return new ExampleDbContext(_dbContextOptions);
}
[Fact]
public async Task Test1()
{
var service = new UserService(CreateDbContext());
var users = await service.GetUsers();
Assert.Equal(new[] { "John", "Bill", "Ilon" }, users);
}
public void Dispose()
{
_databaseInitializer?.RemoveDatabase(CreateDbContext().Database.GetConnectionString());
}
}