-
Notifications
You must be signed in to change notification settings - Fork 2
/
IntegrationTestBase.cs
75 lines (67 loc) · 2.63 KB
/
IntegrationTestBase.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using MccSoft.IntegreSql.EF;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ExampleWeb;
public class IntegrationTestBase : IDisposable
{
protected readonly HttpClient _httpClient;
private readonly IDatabaseInitializer _databaseInitializer;
private readonly string _connectionString;
protected IntegrationTestBase(DatabaseType databaseType)
{
_databaseInitializer = CreateDatabaseInitializer(databaseType);
_connectionString = _databaseInitializer.CreateDatabaseGetConnectionStringSync(
new DatabaseSeedingOptions<ExampleDbContext>(Name: "Integration")
);
var webAppFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.ConfigureAppConfiguration(
(context, configuration) =>
{
configuration.AddInMemoryCollection(
new KeyValuePair<string, string>[] { new("DisableSeed", "true") }
);
}
);
builder.ConfigureServices(services =>
{
var descriptor = services.Single(d =>
d.ServiceType == typeof(DbContextOptions<ExampleDbContext>)
);
services.Remove(descriptor);
services.AddDbContext<ExampleDbContext>(options =>
_databaseInitializer.UseProvider(options, _connectionString)
);
});
});
_httpClient = webAppFactory.CreateDefaultClient();
}
private IDatabaseInitializer CreateDatabaseInitializer(DatabaseType databaseType)
{
return databaseType switch
{
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 void Dispose()
{
_databaseInitializer?.RemoveDatabase(_connectionString);
}
}