-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntegrationTest.cs
103 lines (88 loc) · 3.47 KB
/
IntegrationTest.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using AspNetCore.Testing.MadeEasy.Integration;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
using Xunit.Abstractions;
using Xunit.Sdk;
[assembly: TestFramework("Example.WebApi.Test.WithXunit.GlobalSetup", "Example.WebApi.Test.WithXunit")]
namespace Example.WebApi.Test.WithXunit
{
public class IntegrationTest : TestBase<DatabaseContext, Program>
{
[Fact]
public async Task Person_get_api_should_return_result()
=> await RunTest(
populatedb: async ctx =>
{
var person = PersonFactory.GetPerson();
await ctx.Person!.AddAsync(person);
await ctx.SaveChangesAsync();
},
test: async client =>
{
var response = await client.GetAsync("/person");
var content = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var data = content.RootElement.EnumerateArray().ToList();
Assert.Single(data);
},
cleanDb: async ctx =>
{
ctx.Person.Clear();
await ctx.SaveChangesAsync();
});
protected override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
services.AddEntityFrameworkNpgsql().AddDbContext<DatabaseContext>(
opt =>
{
opt.UseNpgsql(DatabaseManager.ConnectionString, o => o.UseNetTopologySuite());
});
}
}
internal class GlobalSetup : XunitTestFramework, IDisposable
{
private readonly DatabaseManager _dbContainer = new();
public GlobalSetup(IMessageSink messageSink) : base(messageSink)
{
_dbContainer.SpinContainer().Wait();
// Wait for the server to be ready
Task.Delay(5000).Wait();
var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(ConfigureServices);
});
var client = application.CreateClient();
try
{
using var scope = application.Services.CreateScope();
using var ctx = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
ctx.Database.MigrateAsync().Wait();
ctx.Database.OpenConnectionAsync().Wait();
((Npgsql.NpgsqlConnection)ctx.Database.GetDbConnection()).ReloadTypes();
}
catch (Exception)
{
}
}
private static void ConfigureServices(IServiceCollection services)
{
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<DatabaseContext>));
services.Remove(descriptor!);
services.AddEntityFrameworkNpgsql().AddDbContext<DatabaseContext>(
opt =>
{
opt.UseNpgsql(DatabaseManager.ConnectionString, o => o.UseNetTopologySuite());
});
}
public new void Dispose()
{
_dbContainer.StopContainer().Wait();
base.Dispose();
}
}
}