Last active
September 17, 2020 06:08
-
-
Save alex-oswald/8742c2b2aa862874b5ade907e44f819f to your computer and use it in GitHub Desktop.
MockDb Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MockDbHelper | |
{ | |
using Microsoft.Data.Sqlite; | |
using Microsoft.EntityFrameworkCore; | |
using System; | |
public class MockDb<TContext> : IDisposable | |
where TContext : DbContext | |
{ | |
private readonly SqliteConnection _connection = new SqliteConnection("DataSource=:memory:"); | |
public TContext GetContext => (TContext)Activator.CreateInstance(typeof(TContext), GetOptions); | |
public MockDb() | |
{ | |
_connection.Open(); | |
// Create the schema in the database | |
using var context = (TContext)Activator.CreateInstance(typeof(TContext), GetOptions); | |
context.Database.EnsureCreated(); | |
} | |
public void Dispose() | |
{ | |
_connection.Close(); | |
} | |
private DbContextOptions<TContext> GetOptions => | |
new DbContextOptionsBuilder<TContext>() | |
.UseSqlite(_connection) | |
.Options; | |
} | |
} | |
namespace MockDbHelper.Example | |
{ | |
using Moq; | |
using System; | |
using System.Threading.Tasks; | |
using Xunit; | |
public class Tests | |
{ | |
[Fact] | |
public async Task DbTest() | |
{ | |
// Act | |
using var mockDb = new MockDb<DbContext>(); | |
using (var context = mockDb.GetContext) | |
{ | |
// Perform seed actions | |
setupContext.SaveChanges(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment