Skip to content

Instantly share code, notes, and snippets.

@alex-oswald
Last active September 17, 2020 06:08
Show Gist options
  • Save alex-oswald/8742c2b2aa862874b5ade907e44f819f to your computer and use it in GitHub Desktop.
Save alex-oswald/8742c2b2aa862874b5ade907e44f819f to your computer and use it in GitHub Desktop.
MockDb Helper
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