Sub topic 20
Testing Data Access Code
Your app now reads and saves data. Next you need a way to know that this code works, and that it keeps working after you change it. This chapter shows you how to write automated tests for code that uses EF Core.
What a Test Is and Why It Matters
An automated test is a small piece of code that runs your real code and checks the result. A test framework is a library that finds your tests, runs them, and reports which ones passed. This chapter uses xUnit, a popular test framework for .NET.
Data access code is easy to break. If you rename a property or change a query filter, a page can quietly start showing the wrong rows. Tests catch this in seconds, before your users notice.
Choosing What the Tests Talk To
A test needs a database. You have a few options, and each has trade-offs.
| Option | How it works | Good points | Weak points |
|---|---|---|---|
| Real database (same as production) | Tests use a real server, such as SQL Server | Most accurate | Slower, needs setup and cleanup |
| SQLite in-memory | A real SQLite database that lives only in memory | Fast, real SQL, no files | Small differences from other databases |
| EF Core InMemory provider | A fake store with no SQL at all | Very fast | Does not behave like a real database |
| Mocking the context | Replace EF Core with fake objects | No database at all | Tests your fakes, not your queries |
This chapter uses SQLite in-memory. It runs real SQL, so it catches mistakes in your queries. It is also fast enough to give each test a fresh, empty database.
Step 1: Make the Context Testable
Earlier, BloggingContext set its connection string inside OnConfiguring. A test cannot change that. To fix this, add a constructor that accepts options, which are settings passed in from outside. Then use the built-in connection string only when nobody passed options in.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public BloggingContext() { }
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options) { }
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
{
options.UseSqlite("Data Source=blogging.db");
}
}
}IsConfigured is true when options came in through the constructor. Your app keeps working as before, and tests can supply their own database.
Step 2: Write Code Worth Testing
Tests work best on small classes with one clear job. Here is a service, a class that holds your business rules. It receives the context through its constructor, the same way dependency injection supplies it in ASP.NET Core.
using Microsoft.EntityFrameworkCore;
public class BlogService
{
private readonly BloggingContext _db;
public BlogService(BloggingContext db) => _db = db;
public async Task<Blog> AddBlogAsync(string url)
{
if (!url.StartsWith("https://"))
{
throw new ArgumentException("URL must start with https://", nameof(url));
}
var blog = new Blog { Url = url };
_db.Blogs.Add(blog);
await _db.SaveChangesAsync();
return blog;
}
public Task<List<string>> GetUrlsContainingAsync(string text) =>
_db.Blogs
.Where(b => b.Url.Contains(text))
.OrderBy(b => b.Url)
.Select(b => b.Url)
.ToListAsync();
}Add this file to the EfCoreDemo project.
Step 3: Create the Test Project
Run these commands from the folder that contains EfCoreDemo. They create a test project, point it at your app, and add the SQLite provider.
dotnet new xunit -o EfCoreDemo.Tests
cd EfCoreDemo.Tests
dotnet add reference ../EfCoreDemo/EfCoreDemo.csproj
dotnet add package Microsoft.EntityFrameworkCore.SqliteStep 4: Set Up a Fresh Database for Each Test
SQLite keeps an in-memory database alive only while its connection, the open link to the database, stays open. If you let EF Core open and close the connection itself, the data disappears between commands. So the test opens one connection by hand and keeps it open until the test ends.
xUnit creates a new instance of the test class for every test. That means the constructor runs before each test and Dispose runs after it. This gives every test its own empty database, so tests cannot affect each other.
Here is the full test class. Put it in a file named BlogServiceTests.cs in the test project.
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Xunit;
public class BlogServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly DbContextOptions<BloggingContext> _options;
public BlogServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
_options = new DbContextOptionsBuilder<BloggingContext>()
.UseSqlite(_connection)
.Options;
using var context = new BloggingContext(_options);
context.Database.EnsureCreated();
}
private BloggingContext CreateContext() => new BloggingContext(_options);
public void Dispose() => _connection.Dispose();
[Fact]
public async Task AddBlogAsync_SavesBlogToDatabase()
{
using (var context = CreateContext())
{
var service = new BlogService(context);
await service.AddBlogAsync("https://example.com/blog");
}
using (var context = CreateContext())
{
var blog = await context.Blogs.SingleAsync();
Assert.Equal("https://example.com/blog", blog.Url);
}
}
[Fact]
public async Task AddBlogAsync_RejectsNonHttpsUrl()
{
using var context = CreateContext();
var service = new BlogService(context);
await Assert.ThrowsAsync<ArgumentException>(
() => service.AddBlogAsync("http://insecure.com"));
Assert.Equal(0, await context.Blogs.CountAsync());
}
[Fact]
public async Task GetUrlsContainingAsync_ReturnsSortedMatches()
{
using (var context = CreateContext())
{
context.Blogs.AddRange(
new Blog { Url = "https://zeta.example.com" },
new Blog { Url = "https://alpha.example.com" },
new Blog { Url = "https://other.org" });
await context.SaveChangesAsync();
}
using (var context = CreateContext())
{
var service = new BlogService(context);
var urls = await service.GetUrlsContainingAsync("example");
Assert.Equal(
new[] { "https://alpha.example.com", "https://zeta.example.com" },
urls);
}
}
}Run the tests from the test project folder:
dotnet testYou should see three passing tests.
Why the Tests Use `EnsureCreated`
EnsureCreated builds the tables straight from your model and skips migrations. That is fine for a throwaway test database. Do not mix it with migrations on a real database, because a database made by EnsureCreated cannot later be updated with dotnet ef database update.
The Arrange, Act, Assert Pattern
Each test follows three steps:
- Arrange: put the starting data in place.
- Act: call the code you want to test.
- Assert: check that the result is what you expected.
Notice that the tests use a new context for each step. This matters because of change tracking. A context remembers the entities it has already seen, so if you check with the same context, it may hand back its own in-memory copy without asking the database. A fresh context has to read from the database, which proves the data was really saved.
Common Mistakes
- Closing the connection too early. If you pass a connection string instead of an open
SqliteConnection, each command gets a new, empty database. You will see "no such table" errors. - Sharing data between tests. If tests share one database, they can pass alone and fail together. Use a fresh database per test.
- Trusting SQLite for everything. SQLite handles some things differently from SQL Server or PostgreSQL, such as text comparison and date types. For features that depend on your real database, add a few tests that run against that database too.
Exercise
A test passes a connection string "DataSource=:memory:" directly to UseSqlite instead of passing an open SqliteConnection. EnsureCreated runs without error, but the next query fails with "no such table: Blogs". Why, and how do you fix it?
Show answer
An in-memory SQLite database exists only while its connection is open. With a plain connection string, EF Core opens and closes the connection for each operation, so the tables made by EnsureCreated vanish when that connection closes. The fix is to create a SqliteConnection, call Open on it, pass that connection to UseSqlite, and keep it open until the test is disposed.
Exercise
Why does AddBlogAsync_SavesBlogToDatabase check the result with a second context instead of the one used to add the blog?
Show answer
The first context tracks the blog it added and could return that cached object without reading the database. A new context has no tracked entities, so it must query the database. That proves SaveChangesAsync actually stored the row.
Exercise
Write a test named GetUrlsContainingAsync_ReturnsEmptyListWhenNoMatch that adds one blog with the URL "https://other.org" and checks that searching for "example" returns an empty list.
Show answer
Add a [Fact] async Task method. In a first using block, create a context, add new Blog { Url = "https://other.org" }, and await SaveChangesAsync. In a second using block, create a new context and a BlogService, await GetUrlsContainingAsync("example"), and call Assert.Empty on the result.