RepositoryTestBase.cs
2,162 bytes
| 1 | using App.DAL.EF; |
|---|---|
| 2 | using App.Domain; |
| 3 | using App.Domain.Identity; |
| 4 | using Base.Domain; |
| 5 | using Microsoft.Data.Sqlite; |
| 6 | using Microsoft.EntityFrameworkCore; |
| 7 | |
| 8 | namespace App.Tests; |
| 9 | |
| 10 | /// <summary> |
| 11 | /// SQLite in-memory base for DAL tests. Lecture explicitly prefers this over EF's |
| 12 | /// InMemory provider because it enforces foreign keys and behaves like a real RDBMS. |
| 13 | /// </summary> |
| 14 | public abstract class RepositoryTestBase : IDisposable |
| 15 | { |
| 16 | protected readonly AppDbContext Context; |
| 17 | private readonly SqliteConnection _connection; |
| 18 | |
| 19 | protected RepositoryTestBase() |
| 20 | { |
| 21 | _connection = new SqliteConnection("Data Source=:memory:"); |
| 22 | _connection.Open(); |
| 23 | |
| 24 | var options = new DbContextOptionsBuilder<AppDbContext>() |
| 25 | .UseSqlite(_connection) |
| 26 | .Options; |
| 27 | |
| 28 | Context = new AppDbContext(options); |
| 29 | Context.Database.EnsureCreated(); |
| 30 | } |
| 31 | |
| 32 | /// <summary>Seeds a Currency, an AppUser and a Trip; returns them. Trip has the user as organizer participant.</summary> |
| 33 | protected async Task<(Currency currency, AppUser user, Trip trip)> SeedTripAsync() |
| 34 | { |
| 35 | var currency = new Currency { Code = "EUR", Name = new LangStr("Euro"), Symbol = "€" }; |
| 36 | var user = new AppUser |
| 37 | { |
| 38 | Id = Guid.NewGuid(), |
| 39 | UserName = "test@example.com", |
| 40 | Email = "test@example.com", |
| 41 | FirstName = "Test", |
| 42 | LastName = "User" |
| 43 | }; |
| 44 | var trip = new Trip |
| 45 | { |
| 46 | Name = "Paris", |
| 47 | Destination = "France", |
| 48 | DefaultCurrencyId = currency.Id, |
| 49 | CreatedById = user.Id |
| 50 | }; |
| 51 | Context.Currencies.Add(currency); |
| 52 | Context.Users.Add(user); |
| 53 | Context.Trips.Add(trip); |
| 54 | Context.TripParticipants.Add(new TripParticipant |
| 55 | { |
| 56 | TripId = trip.Id, |
| 57 | UserId = user.Id, |
| 58 | Role = EParticipantRole.Organizer, |
| 59 | IsActive = true |
| 60 | }); |
| 61 | await Context.SaveChangesAsync(); |
| 62 | return (currency, user, trip); |
| 63 | } |
| 64 | |
| 65 | public void Dispose() |
| 66 | { |
| 67 | Context.Dispose(); |
| 68 | _connection.Dispose(); |
| 69 | GC.SuppressFinalize(this); |
| 70 | } |
| 71 | } |
| 72 | |