Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created January 12, 2017 12:44
Show Gist options
  • Select an option

  • Save MikeMKH/1ca3323f73ecb0dcc4b2502afbbd8c62 to your computer and use it in GitHub Desktop.

Select an option

Save MikeMKH/1ca3323f73ecb0dcc4b2502afbbd8c62 to your computer and use it in GitHub Desktop.
Entity Framework Core example using an InMemoryDatabse along with xUnit.
using System.Linq;
using Data;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Tests
{
public class UserContextTests
{
public UserContextTests()
{
}
[Fact]
public void WhenUserIsInsertedItCanBeSelected()
{
var user = new User
{
Id = 1,
FirstName = "Hello",
LastName = "World"
};
var sut = GetInstance();
sut.Users.Add(user);
sut.SaveChanges();
var retrieved = sut.Users.First();
Assert.Equal(user, retrieved);
}
[Fact]
public void GivenContextItMustBeEmpty()
{
var sut = GetInstance();
Assert.Equal(0, sut.Users.Count());
}
private UserContext GetInstance()
{
var builder = new DbContextOptionsBuilder<UserContext>();
builder.UseInMemoryDatabase();
var context = new UserContext(builder.Options);
context.Database.EnsureDeleted(); // as if having to have a method like this was not lame enough
return context;
}
}
}
namespace Data
{
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
namespace Data
{
public class UserContext : DbContext
{
public UserContext(DbContextOptions<UserContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseInMemoryDatabase();
}
public DbSet<User> Users { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment