blob: dfadd1ae33c735788ff2208ecaeab759857e9c1a (
plain)
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
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using Timeline.Entities;
using Timeline.Services;
using Timeline.Tests.Mock.Data;
using Timeline.Tests.Mock.Services;
using Xunit.Abstractions;
namespace Timeline.Tests.Helpers
{
public class MyWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IClock, TestClock>();
});
}
}
public static class WebApplicationFactoryExtensions
{
public static WebApplicationFactory<TEntry> WithTestConfig<TEntry>(this WebApplicationFactory<TEntry> factory, ITestOutputHelper outputHelper, out Action disposeAction) where TEntry : class
{
// We should keep the connection, so the database is persisted but not recreate every time.
// See https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite#writing-tests .
SqliteConnection _databaseConnection = new SqliteConnection("Data Source=:memory:;");
_databaseConnection.Open();
{
var options = new DbContextOptionsBuilder<DatabaseContext>()
.UseSqlite(_databaseConnection)
.Options;
using (var context = new DatabaseContext(options))
{
context.Database.EnsureCreated();
context.Users.AddRange(MockUsers.Users);
context.SaveChanges();
};
}
disposeAction = () =>
{
_databaseConnection.Close();
_databaseConnection.Dispose();
};
return factory.WithWebHostBuilder(builder =>
{
builder
.ConfigureLogging(logging =>
{
logging.AddXunit(outputHelper);
})
.ConfigureServices(services =>
{
services.AddEntityFrameworkSqlite();
services.AddDbContext<DatabaseContext>(options =>
{
options.UseSqlite(_databaseConnection);
});
});
});
}
}
}
|