-
Notifications
You must be signed in to change notification settings - Fork 2
/
IntegrationTestAdvancedSeedingExample.cs
81 lines (71 loc) · 2.67 KB
/
IntegrationTestAdvancedSeedingExample.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
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using MccSoft.IntegreSql.EF;
using MccSoft.IntegreSql.EF.DatabaseInitialization;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace ExampleWeb;
public class IntegrationTestAdvancedSeedingExample : IDisposable
{
protected HttpClient _httpClient = null!;
private readonly IDatabaseInitializer _databaseInitializer;
private readonly string _connectionString;
public IntegrationTestAdvancedSeedingExample()
{
_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 }
);
_connectionString = _databaseInitializer.CreateDatabaseGetConnectionStringSync(
new DatabaseSeedingOptions<ExampleDbContext>(
Name: nameof(IntegrationTestAdvancedSeedingExample),
SeedingFunction: async (dbContext) =>
{
CreateWebApplication(dbContext.Database.GetConnectionString()!);
await SeedData();
},
DisableEnsureCreated: true
)
);
CreateWebApplication(_connectionString);
}
private async Task SeedData()
{
await _httpClient.PostAsJsonAsync("/users", new { Name = "qwe" });
}
private WebApplicationFactory<Program> CreateWebApplication(string connectionString)
{
var webAppFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
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();
return webAppFactory;
}
[Fact]
public async Task Test()
{
var result = await _httpClient.GetFromJsonAsync<List<string>>("/users-from-service");
Assert.Equal(new string[] { "John", "Bill", "Ilon", "qwe" }, result);
}
public void Dispose()
{
_databaseInitializer?.RemoveDatabase(_connectionString);
}
}