In my new project, we use EF Core for ORM. We have unit tests for the repository layer where the DbContext is used. I’m going to show how to use in-memory database to create the DbContext.
I’ll use the model below for example
public class Article
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ArticleNumber { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
}
The DbContext looks like below
public class ArticleDbContext : DbContext
{
public DbSet<Article> Articles { get; set; }
// More DbSet goes here
public ArticleDbContext(DbContextOptions<ArticleDbContext> options) : base(options)
{}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Model creating logic goes here
}
}
I have a ArticleRepository as below
public interface IArticleRepository
{
Article GetById(Guid id);
}
public class ArticleRepository : IArticleRepository
{
private readonly ArticleDbContext _context;
public ArticleRepository(ArticleDbContext context)
{
_context = context;
}
public Article GetById(Guid id)
{
return _context.FirstOrDefault(x => x.Id == id);
}
}
In the test project, I have a InMemoryDbContextFactory which looks like below
public class InMemoryDbContextFactory
{
public ArticleDbContext GetArticleDbContext()
{
var options = new DbContextOptionsBuilder<ArticleDbContext>()
.UseInMemoryDatabase(databaseName: "InMemoryArticleDatabase")
.Options;
var dbContext = new ArticleDbContext(options);
return dbContext;
}
}
How it is used in a unit test
[TestFixture]
public class ArticleRepositoryTests
{
private readonly ArticleDbContext _dbContext;
private readonly IArticleRepository _articleRepository;
public ArticleRepositoryTests()
{
_dbContext = new InMemoryDbContextFactory().GetArticleDbContext();
_articleRepository = new ArticleRepository(_dbContext);
}
[Test]
public GetById_Should_Return_Correct_Article()
{
// Arrange
var articleId = Guid.NewGuid();
var articles = new List<Article>
{
new Article { Id = Guid.NewGuid() },
new Article { Id = Guid.NewGuid() },
new Article { Id = articleId },
new Article { Id = Guid.NewGuid() }
};
_dbContext.Articles.AddRange(articles);
_dbContext.SaveChanges();
// Act
var actual = await _articleRepository.GetById(articleId);
// Assert
actual.Id.Should().Be(articleId);
}
}
