Skip to content

Testing: Getting Started ​

Introduction ​

The DotBlaze.Testing package is Laravel's testing layer for DotBlaze: it boots your whole application in memory (on ASP.NET Core's WebApplicationFactory), sends requests with ActingAs and fluent assertions such as AssertRedirect and AssertSessionHasErrors, checks the database with AssertDatabaseHas, and drives live components. The facades' fakes (Mail.Fake(), Queue.Fake(), ...) record what your code did instead of doing it, also inside the requests a test sends.

csharp
[Fact]
public async Task Authors_can_publish_a_post()
{
    var user = await app.Run(() => User.Factory().Create());

    var response = await app.Client().ActingAs(user).Post("/posts", new { Title = "Hello", Body = "World" });

    response.AssertRedirect().AssertSessionHas("status", "Post created.");
    await app.AssertDatabaseHas("posts", new { title = "Hello", user_id = user.Id });
}

The examples on these pages come from tests/SampleApp.Tests, the test suite of the sample blog in the DotBlaze repository. The package works with any test framework; the examples use xUnit.

Creating a Test Project ​

Create an xUnit project next to the app, and reference the app and DotBlaze.Testing:

shell
# From the directory containing the App application directory:
dotnet new xunit -o App.Tests --framework net10.0
dotnet add App.Tests reference App/App.csproj
dotnet add App.Tests package DotBlaze.Testing

TestApp<Program> needs to see the app's Program class. DotBlaze's Program.cs ends with a partial declaration for exactly this reason:

csharp
var app = DotBlaze.Application.Create(args);
app.Run();

public partial class Program;

The Application Fixture ​

TestApp<Program> is the application under test. Use it as a class fixture, so the app boots once per test class:

csharp
using DotBlaze.Testing;

public class PostTest(TestApp<Program> app) : IClassFixture<TestApp<Program>>, IAsyncLifetime
{
    public Task InitializeAsync() => app.RefreshDatabase();   // before each test
    public Task DisposeAsync() => Task.CompletedTask;

    [Fact]
    public async Task Home_page_loads() => (await app.Client().Get("/")).AssertOk().AssertSee("Welcome");
}

For tests it sets:

SettingValue
EnvironmentTesting
DatabaseA new SQLite file in a temporary directory, for each TestApp
mail.defaultarray: nothing is sent; messages are kept in memory
queue.defaultsync: jobs run during the request
cache.defaultmemory
hashing.iterations1000, so password hashing is fast

In the Testing environment, a request that throws answers 500 with the exception and stack trace in its body, so a failing assertion shows what went wrong.

RefreshDatabase() drops every table and runs the migrations again, like Laravel's RefreshDatabase trait. Call it before each test (as above) for a clean database, or once in a derived fixture when the tests in a class may share data.

Changing Settings ​

Derive from TestApp<Program> and override Settings. Keys use : between levels and override the config/*.cs classes:

csharp
public class BlogApp : TestApp<Program>, IAsyncLifetime
{
    protected override void Settings(IDictionary<string, string?> settings)
    {
        base.Settings(settings);
        settings["database:default"] = Environment.GetEnvironmentVariable("DOTBLAZE_TEST_DB") ?? "sqlite";
        settings["queue:default"] = "database";
    }

    public Task InitializeAsync() => RefreshDatabase();
    Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
}

TestApp is a WebApplicationFactory<Program>, so everything ASP.NET Core offers there (ConfigureWebHost, WithWebHostBuilder, Services, CreateClient) still works.

Writing Tests ​

HTTP Tests ​

Most tests send requests to the app and check the response, see HTTP Tests.

Testing Code Outside a Request ​

Models, facades, jobs, and seeders need an active service scope. app.Run provides one, and returns the closure's result:

csharp
[Fact]
public async Task Latest_scope_orders_newest_first()
{
    var titles = await app.Run(async () =>
    {
        var user = await User.Factory().Create();
        await Post.Factory().For(user).Sequence(new { Title = "First" }, new { Title = "Second" }).CreateMany(2);
        return (await Post.Scope(Post.Latest).Get()).Pluck(p => p.Title);
    });

    Assert.Equal("Second", titles.First());
}

See Database Testing for factories and database assertions, and Fakes for replacing mail, notifications, the queue, events, logging, the HTTP client, storage, and the cache.

Running Tests ​

shell
dotnet test

Running Tests in Parallel ​

xUnit runs test classes in parallel. Each TestApp has its own SQLite file, so that is safe. Facade fakes are stored per async flow, so two tests faking the same facade at the same time do not see each other's records.

When test classes share one database server (see below), put them in a collection with parallelization turned off:

csharp
[CollectionDefinition("app", DisableParallelization = true)]
public sealed class AppCollection;

[Collection("app")]
public class BlogFlowTest(BlogApp app) : IClassFixture<BlogApp>
{
    // ...
}

Testing Against Other Databases ​

The BlogApp fixture above reads the driver from the DOTBLAZE_TEST_DB environment variable. Connection settings come from environment variables, which override config/Database.cs:

shell
DOTBLAZE_TEST_DB=pgsql \
database__connections__pgsql__host=localhost \
database__connections__pgsql__password=secret \
dotnet test

WARNING

RefreshDatabase() drops every table on the default connection. Point tests at a database that exists only for testing.

Complete Example and First Test Run ​

The complete blog HTTP test includes all imports, its test class, fixture construction, database reset, factory-created users, route calls, and assertions. It tests creation, display, editing, deletion, validation, CSRF, and another user's denied access.

Run from the directory containing Blog and Blog.Tests:

shell
dotnet test Blog.Tests --filter FullyQualifiedName~PostTest

Expected: one passing end-to-end test. Related standalone examples verify transaction rollback, foreign-key cascades, model updates, password casts, and hidden JSON fields.

Keep test projects outside the web application's directory. If you intentionally nest tests, explicitly remove their files from the web project's compile/content globs. The fixture examples use xUnit 2's Task-based IAsyncLifetime; do not mix them with xUnit 3's different lifetime signatures.