-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWebApplicationFactory.cs
More file actions
54 lines (45 loc) · 1.74 KB
/
WebApplicationFactory.cs
File metadata and controls
54 lines (45 loc) · 1.74 KB
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
using EssentialCSharp.Web.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace EssentialCSharp.Web.Tests;
internal sealed class WebApplicationFactory : WebApplicationFactory<Program>
{
private static string SqlConnectionString => $"DataSource=file:{Guid.NewGuid()}?mode=memory&cache=shared";
private SqliteConnection? _Connection;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
ServiceDescriptor? descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<EssentialCSharpWebContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
_Connection = new SqliteConnection(SqlConnectionString);
_Connection.Open();
services.AddDbContext<EssentialCSharpWebContext>(options =>
{
options.UseSqlite(_Connection);
});
using ServiceProvider serviceProvider = services.BuildServiceProvider();
using IServiceScope scope = serviceProvider.CreateScope();
IServiceProvider scopedServices = scope.ServiceProvider;
EssentialCSharpWebContext db = scopedServices.GetRequiredService<EssentialCSharpWebContext>();
db.Database.EnsureCreated();
});
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_Connection?.Dispose();
_Connection = null;
}
}
}