-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDatabaseFakes.cs
More file actions
75 lines (69 loc) · 2.87 KB
/
DatabaseFakes.cs
File metadata and controls
75 lines (69 loc) · 2.87 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
66
67
68
69
70
71
72
73
74
75
using System.Data.Common;
using Dotnet.Samples.AspNetCore.WebApi.Data;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities
{
/// <summary>
/// A Fake is a working implementation that’s simpler than the real one.
/// It usually has some “real” logic but is not suitable for production
/// (e.g., an in‑memory database instead of a full SQL Server). Fakes are
/// useful when you need behavior that’s closer to reality but still want
/// to avoid external dependencies.
/// </summary>
public static class DatabaseFakes
{
/// <summary>
/// Creates an in-memory SQLite connection and DbContext options for testing.
/// The connection remains open for the lifetime of the test.
/// </summary>
/// <returns>A tuple containing the SQLite connection and DbContext options.</returns>
public static (DbConnection, DbContextOptions<PlayerDbContext>) CreateSqliteConnection()
{
var dbConnection = new SqliteConnection("Filename=:memory:");
dbConnection.Open();
var dbContextOptions = new DbContextOptionsBuilder<PlayerDbContext>()
.UseSqlite(dbConnection)
.Options;
return (dbConnection, dbContextOptions);
}
/// <summary>
/// Creates a PlayerDbContext instance with the specified options.
/// </summary>
/// <param name="dbContextOptions">The DbContext options to use.</param>
/// <returns>A new PlayerDbContext instance.</returns>
public static PlayerDbContext CreateDbContext(
DbContextOptions<PlayerDbContext> dbContextOptions
)
{
return new PlayerDbContext(dbContextOptions);
}
/// <summary>
/// Creates the database schema for the test database.
/// Extension method for PlayerDbContext.
/// </summary>
/// <param name="context">The PlayerDbContext instance.</param>
public static void CreateTable(this PlayerDbContext context)
{
using var cmd = context.Database.GetDbConnection().CreateCommand();
cmd.CommandText =
@"
CREATE TABLE players (
id INTEGER PRIMARY KEY,
firstName TEXT NOT NULL,
/* ... other columns ... */
)";
cmd.ExecuteNonQuery();
}
/// <summary>
/// Seeds the test database with the starting 11 players.
/// Extension method for PlayerDbContext.
/// </summary>
/// <param name="context">The PlayerDbContext instance.</param>
public static void Seed(this PlayerDbContext context)
{
context.Players.AddRange(PlayerFakes.MakeStarting11());
context.SaveChanges();
}
}
}