-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSqliteTestStore.cs
More file actions
65 lines (52 loc) · 1.89 KB
/
SqliteTestStore.cs
File metadata and controls
65 lines (52 loc) · 1.89 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
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) Fusonic GmbH. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Fusonic.Extensions.UnitTests.EntityFrameworkCore.Tests;
public class SqliteTestStore : ITestStore, IDisposable
{
private SqliteConnection? connection;
public bool CreateDatabaseCalled { get; private set; }
public bool DropDatabaseCalled { get; private set; }
public string TestDbName { get; private set; } = null!;
public string ConnectionString => $"Data Source={TestDbName};Mode=Memory;Cache=Shared";
public async Task CreateDatabase()
{
if (CreateDatabaseCalled)
return;
CreateDatabaseCalled = true;
await using var dbContext = CreateDbContext();
await dbContext.Database.EnsureCreatedAsync();
}
public void DropDatabase()
{
DropDatabaseCalled = true;
using var dbContext = CreateDbContext();
dbContext.Database.EnsureDeleted();
}
private TestDbContext CreateDbContext()
=> new(new DbContextOptionsBuilder<TestDbContext>()
.UseSqlite(ConnectionString)
.AddInterceptors(new ConnectionOpeningInterceptor(CreateDatabase))
.Options);
public void OnTestConstruction()
{
TestDbName = $"Test_{Guid.NewGuid():N}";
CreateDatabaseCalled = false;
DropDatabaseCalled = false;
// Need to maintain an open connection spanning a test to avoid dropping the in-memory DB.
connection = new SqliteConnection(ConnectionString);
connection.Open();
}
public async Task OnTestEnd()
{
DropDatabase();
connection?.Close();
await Task.CompletedTask;
}
public void Dispose()
{
connection?.Dispose();
GC.SuppressFinalize(this);
}
}