Welcome to this comprehensive guide on using an InMemory database for testing in ASP .NET! This tutorial is designed to be accessible for beginners and intermediates alike, with a focus on practical, real-world examples.
In this lesson, we will explore how to leverage InMemory databases for testing in ASP .NET applications. We'll cover:
An InMemory database stores data entirely within a computer's memory, providing a faster alternative to traditional databases that store data on disk. This makes InMemory databases ideal for testing, as they can greatly speed up the process and help reduce the impact on production data.
To set up an InMemory database in ASP .NET, we will use the Microsoft.EntityFrameworkCore.InMemory NuGet package. Let's start by adding this package to our project:
Install-Package Microsoft.EntityFrameworkCore.InMemory
Now, let's create a new DbContext that inherits from Microsoft.EntityFrameworkCore.DbContext and uses the InMemoryDatabaseFactory:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.InMemory;
public class InMemoryDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("InMemoryTestDb");
}
public DbSet<MyEntity> MyEntities { get; set; }
}In this example, MyEntity represents a simple entity that we'll create shortly.
With our InMemory database set up, let's create a simple entity and perform CRUD operations:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class InMemoryDbContext : DbContext
{
// ...
public DbSet<MyEntity> MyEntities { get; set; }
// ...
}Now, we can create, read, update, and delete instances of MyEntity:
var context = new InMemoryDbContext();
// Create
context.MyEntities.Add(new MyEntity { Id = 1, Name = "John" });
context.SaveChanges();
// Read
var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);
// Update
entity.Name = "Jane";
context.SaveChanges();
// Delete
context.MyEntities.Remove(entity);
context.SaveChanges();Now that we understand how to set up and perform CRUD operations with an InMemory database, let's explore how to use it for testing. Here's a simple example of a unit test using an InMemory database:
public class MyEntityTest
{
[Fact]
public void Test_MyEntity()
{
var options = new DbContextOptionsBuilder<InMemoryDbContext>()
.UseInMemoryDatabase("TestMyEntityDb")
.Options;
using (var context = new InMemoryDbContext(options))
{
// Setup
context.MyEntities.Add(new MyEntity { Id = 1, Name = "John" });
context.SaveChanges();
// Test
var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);
// Assert
Assert.NotNull(entity);
Assert.Equal("John", entity.Name);
}
}
}In this example, we create an InMemory database specifically for testing, add a sample entity, and then perform an assertion to verify that the entity was added correctly.
Which NuGet package do we use to set up an InMemory database in ASP .NET?