Hmz.Core.Testing 0.1.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Hmz.Core.Testing --version 0.1.1
                    
NuGet\Install-Package Hmz.Core.Testing -Version 0.1.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hmz.Core.Testing" Version="0.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hmz.Core.Testing" Version="0.1.1" />
                    
Directory.Packages.props
<PackageReference Include="Hmz.Core.Testing" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hmz.Core.Testing --version 0.1.1
                    
#r "nuget: Hmz.Core.Testing, 0.1.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hmz.Core.Testing@0.1.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hmz.Core.Testing&version=0.1.1
                    
Install as a Cake Addin
#tool nuget:?package=Hmz.Core.Testing&version=0.1.1
                    
Install as a Cake Tool

Hmz.Core.Testing

Hmz.Core.Testing contains deliberately small helpers for ASP.NET Core functional and integration test projects. Most abstractions are provider-neutral; the optional PostgreSQL lifecycle is grouped under the Hmz.Core.Testing.PostgreSql subnamespace in the same package.

Test authentication

Register the test scheme from WebApplicationFactory.ConfigureWebHost:

builder.ConfigureTestServices(services =>
{
    services.AddHmzTestAuthentication();
});

Create an authenticated client without depending on a live identity provider:

var client = factory.CreateClient()
    .AuthenticateAs("test-admin", "ADMIN");

The generated header uses TestBearer <subject>|<comma-separated-roles>. HmzTestAuthenticationHandler emits sub, ClaimTypes.NameIdentifier, ClaimTypes.Role, and roles claims. The application must still resolve the subject and load application permissions through its real middleware and database. Never enable this scheme in an application runtime environment.

HTTP response helpers

Use strict shared response helpers while keeping endpoint methods and DTOs in the consuming test project:

using Hmz.Core.Testing.Http;

using var response = await client.PostAsJsonAsync("/api/v1/widgets", request);
var widget = await response.ReadRequiredJsonAsync<WidgetResponse>(
    HttpStatusCode.Created,
    cancellationToken: cancellationToken);
var entityTag = response.RequireEntityTag();

ReadRequiredJsonAsync<T> validates the exact expected status, requires a non-empty/non-null JSON payload, and bounds response-body diagnostics. Do not call it for documented 204 or 304 responses.

When one fixture intentionally shares an HttpClient, call ResetScenarioHeaders() between scenarios to clear authentication and conditional request headers. Stable defaults such as Accept are preserved. This helper resets scenario-sensitive headers only; database reset and application caches remain the consuming fixture's responsibility.

Functional API client base

An application may derive its typed test client from FunctionalApiClientBase:

public sealed partial class FunctionalApiClient(HttpClient client)
    : FunctionalApiClientBase(client)
{
}

Endpoint partials then use the protected Client property, while test methods can use the inherited fluent AuthenticateAs(...) method. Core owns only construction, null validation, access to the shared client, and test authentication. Routes, request/response DTOs, and endpoint methods remain in the application.

Generic host and fixture contracts

Derive an application factory from ApiWebApplicationFactory<TProgram>:

public sealed class ApiWebApplicationFactory(string connectionString)
    : ApiWebApplicationFactory<Program>
{
    // Optional:
    // protected override string TestEnvironment => Environments.Development;

    protected override void ConfigureApplicationWebHost(IWebHostBuilder builder)
    {
        // Application settings, DbContexts and service replacements stay here.
    }
}

The default environment is "TestEnvironment", exposed by ApiWebApplicationFactory<TProgram>.DefaultTestEnvironment. Override the protected TestEnvironment property only when a test must execute another environment's startup path.

Implement IFunctionalTestFixture<TWebApplicationFactory, TApiClient> on the application fixture, then derive the application's test base from FunctionalTestBase<TFixture, TWebApplicationFactory, TApiClient>. The Core base clears scenario-sensitive request headers before each case and calls the fixture's ResetAsync() afterward.

TProgram keeps host typing compile-safe. TWebApplicationFactory keeps the fixture and base compile-safe without reflection or casts.

Functional-test lifecycle

The intended xUnit v3 design has two nested lifecycles:

  1. Assembly fixture — once for the test executable. The concrete fixture derives from PostgreSqlFunctionalTestFixtureBase and is registered with [assembly: AssemblyFixture(...)]. Its constructor only defines the container. xUnit then calls its InitializeAsync() once to start PostgreSQL, create and start the application factory, run application initialization/migrations, seed core and test data, open the Respawn connection, and create one shared HttpClient and typed API client.
  2. Test class instance — once per test case. xUnit constructs the test class, then Core's FunctionalTestBase.InitializeAsync() clears scenario-sensitive headers before the test method. After the method, FunctionalTestBase.DisposeAsync() calls the shared fixture's ResetAsync(). For PostgreSQL this clears headers again, runs Respawn, reruns application/core seeding, recreates test data, and invokes AfterResetAsync().

The container, database, application host/service provider, factory, HttpClient, typed API client, open Npgsql connection, and Respawner are therefore shared across test cases. Test-specific headers and mutable database rows are not shared. The fixture disposes the client, database connection, application factory, and container once after the assembly finishes.

The PostgreSQL hooks run at these frequencies:

Hook Frequency Responsibility
CreateContainer() Fixture construction, once Define the disposable PostgreSQL container; it is not started yet.
CreateFactory(...) Assembly startup, once Create the application-specific in-process host.
InitializeApplicationServicesAsync(...) Assembly startup, once Prepare the disposable database, normally by applying module migrations.
SeedApplicationAsync(...) Startup and after every test Restore idempotent application/core data.
SeedTestDataAsync(...) Startup and after every test Restore test-only actors and scenario baseline data.
CreateRespawnerOptions() Assembly startup, once Select schemas and tables excluded from reset.
CreateApiClient(...) Assembly startup, once Wrap the shared HttpClient.
BeforeResetAsync(...) Before every database reset Quiesce and drain application-owned workers before Respawn.
AfterResetAsync(...) After every test reset Refresh any application-specific state not covered by reseeding.

Because reset happens after every test, the first case receives the assembly-startup baseline and each later case receives the freshly reset and reseeded baseline left by the previous case. The shared-database model must remain serialized. Parallel workers require an independently migrated/seeded database, host, client, connection, and Respawner per worker.

An environment-specific startup test may create an additional factory that reuses the fixture's connection string. That factory is owned and disposed by that test; it does not replace the assembly's shared factory. The normal per-test reset still runs afterward.

Shared-host state and background work

Respawn resets PostgreSQL rows; it cannot reset state held elsewhere. Reusing one WebApplicationFactory means all host-level singleton and background state also lives for the whole assembly. Typical examples are IMemoryCache or the L1 portion of HybridCache, singleton dictionaries/registries, channels/queues, timers, rate limiters, circuit breakers, and IHostedService/BackgroundService instances.

A consuming fixture must make every such component safe with one of these explicit policies:

  • invalidate or clear state in SeedTestDataAsync() or AfterResetAsync();
  • replace it in ConfigureTestServices with a resettable test implementation;
  • disable an unrelated hosted service for this suite;
  • expose a deterministic drain/wait hook and await all relevant work from BeforeResetAsync() before Respawn;
  • use a separate disposable external dependency and purge its test namespace; or
  • use a fresh host/database per test or per isolated collection when reliable reset is not possible.

Never start untracked fire-and-forget work from a request under test. Background work can continue while ResetAsync() truncates or reseeds the database and can make the next test flaky or repopulate rows after reset. Tests that verify a worker should enqueue work, await a deterministic completion signal, assert its effects, and ensure the queue is empty before returning.

Cache keys should be test-namespace aware when a real distributed cache is in scope. Database reset alone does not clear Redis or another L2 cache. AfterResetAsync() should remove the suite's key prefix/tags; never flush a shared developer or production cache. If the application has no complete reset contract, prefer replacing the cache or creating a fresh host over relying on expiration.

BeforeResetAsync() and AfterResetAsync() receive CancellationToken.None because xUnit's per-test disposal contract does not provide a cancellation token and cleanup must not be skipped merely because the test's request token was canceled. Implementations should enforce their own bounded timeout and throw a diagnostic failure if a worker cannot become idle; never wait forever.

Deliberate package boundary

The package owns the small reusable PostgreSQL container/Npgsql/Respawn lifecycle under its PostgreSql folder. It does not own application migration sets, schemas, ignored tables, seed data, actors, cache invalidation, or parallel-worker allocation. Other providers remain opt-in and should use their own folder while small; extract an independent provider package only when its size, dependencies, release cadence, or consumers justify it.

It does not own the concrete xUnit assembly fixture, concrete application factory, endpoint-specific client methods, roles, permissions, test actors, or seed data. Core owns only their generic contracts and lifecycle shell; the application owns all host configuration, infrastructure and API behavior.

PostgreSQL fixture

The Hmz.Core.Testing.PostgreSql namespace is a folder/subnamespace in this package, not a separate package. Derive from PostgreSqlFunctionalTestFixtureBase<TWebApplicationFactory, TApiClient> to reuse PostgreSQL Testcontainers, connection, Respawn reset, and disposal plumbing. Override application schemas, migration-history exclusions, migrations, seeders, actors, caches, factory, and API-client construction.

Keep another provider in its own subfolder while its implementation remains small. Extract a separate provider package only when its size, dependencies, release cadence, or consumer set justifies independent versioning.

Pack for manual publication

From the repository root:

dotnet restore .\Hmz.Core.slnx
dotnet build .\Hmz.Core.slnx --configuration Release --no-restore
dotnet pack .\Hmz.Core.Testing\Hmz.Core.Testing.csproj `
  --configuration Release `
  --no-build `
  --output .\artifacts\packages

Current version: 0.1.1, prepared for NuGet publication. Inspect the package, then publish it using the maintainer's selected NuGet source and credentials. Publication is intentionally not automated by this repository. Never republish a released version; advance the package version and changelog for any subsequent artifact.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.3 95 11/8/2026
0.1.2 109 11/1/2026
0.1.1 104 10/21/2026
0.1.0 121 9/26/2026