Skip to content

Database Testing ​

Introduction ​

Database tests run your migrations against a throwaway database, create the data each test needs with factories, and check what ended up in the tables with AssertDatabaseHas and friends. All of it is on the TestApp fixture.

Resetting the Database ​

Each TestApp has its own SQLite file. RefreshDatabase() drops every table and runs all migrations, like Laravel's RefreshDatabase and migrate:fresh. Call it before each test for a clean database:

csharp
public class PostTest(TestApp<Program> app) : IClassFixture<TestApp<Program>>, IAsyncLifetime
{
    public Task InitializeAsync() => app.RefreshDatabase();
    public Task DisposeAsync() => Task.CompletedTask;
}

When it is enough to start each test class with a fresh database, call it once in the fixture's own InitializeAsync instead, and write tests that do not depend on each other's rows.

The Migrator service also has Migrate(), Rollback(all: false), and Status(), to test migrations themselves:

csharp
await app.Run(() => ServiceScope.Current.GetRequiredService<Migrator>().Rollback(all: true));

Creating Test Data ​

app.Run runs code with the application's services, so models and factories work as in a request, and returns the result:

csharp
[Fact]
public async Task Deleting_a_user_deletes_their_posts()
{
    var user = await app.Run(() => User.Factory().Has(Post.Factory().Count(2)).Create());

    await app.Run(() => user.Delete());

    await app.AssertDatabaseMissing("posts", new { user_id = user.Id });
}

Each app.Run is its own scope, like a separate request: models loaded in one are not tracked in the next. Data created there is visible to requests the test sends afterwards, since both use the same database.

Running Seeders ​

Resolve SeederRunner and call Run, with no argument for DatabaseSeeder or with a seeder's class name:

csharp
await app.Run(async () =>
{
    var seeders = ServiceScope.Current.GetRequiredService<SeederRunner>();

    await seeders.Run();               // DatabaseSeeder
    await seeders.Run("PostSeeder");   // one seeder by class name
});

Run returns the full name of the seeder that ran, and throws an InvalidOperationException when the name is unknown or ambiguous.

Available Assertions ​

Assertion
AssertDatabaseHas(table, conditions)A row matches all the column values: new { email = "ali@example.com" }. The failure message shows a few rows of the table.
AssertDatabaseMissing(table, conditions)No row matches.
AssertDatabaseCount(table, count)The table has exactly that many rows.
AssertDatabaseEmpty(table)The table has no rows.
AssertModelExists(model)The model's row exists (by its key).
AssertModelMissing(model)The model's row is gone (a soft-deleted row still exists).
AssertSoftDeleted(model)The row exists and has DeletedAt set.
AssertNotSoftDeleted(model)The row exists and is not soft deleted.

The table assertions take an optional connection name. Conditions use column names (user_id), since they query the table directly.

csharp
await app.AssertDatabaseHas("posts", new { title = "Hello", user_id = user.Id });
await app.AssertDatabaseCount("users", 3);
await app.AssertSoftDeleted(book);

Running Queued Jobs ​

TestApp uses the sync queue driver, so jobs run during the request. To test the database driver, set queue:default to database in your fixture's settings (the jobs and failed_jobs migration must be part of your app) and process jobs with the Worker service. RunNext processes one job from a queue in its own scope and returns false when the queue is empty:

csharp
var worker = app.Services.GetRequiredService<Worker>();

while (await worker.RunNext("default")) { }

Jobs that fail permanently end up in failed_jobs, which you can check with AssertDatabaseHas("failed_jobs", ...). To check that a job was dispatched without running it, use Queue.Fake().

Complete Example: Foreign-Key Behavior ​

This uses exactly the walkthrough's model and migration, which declare cascading deletion. It does not require a post factory or an inverse User.Posts navigation.

csharp
// Blog.Tests/CascadeTest.cs
using Blog.Models;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class CascadeTest
{
    [Fact]
    public async Task Deleting_the_author_removes_their_posts()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        var user = await app.Run(() => User.Factory().Create());
        var post = await app.Run(async () =>
        {
            var value = new Post { UserId = user.Id, Title = "Owned post", Body = "Body" };
            await value.Save();
            return value;
        });
        await app.AssertModelExists(post);
        await app.Run(() => user.Delete());
        await app.AssertModelMissing(user);
        await app.AssertModelMissing(post);
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~CascadeTest after creating the test project. Expected: one passing test against isolated SQLite. It verifies the migration's foreign key, not application-level deletion callbacks.