Created
January 12, 2017 12:44
-
-
Save MikeMKH/1ca3323f73ecb0dcc4b2502afbbd8c62 to your computer and use it in GitHub Desktop.
Entity Framework Core example using an InMemoryDatabse along with xUnit.
This file contains hidden or 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
| 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; | |
| } | |
| } | |
| } |
This file contains hidden or 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 Data | |
| { | |
| public class User | |
| { | |
| public int Id { get; set; } | |
| public string FirstName { get; set; } | |
| public string LastName { get; set; } | |
| } | |
| } |
This file contains hidden or 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
| 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