Hmz.Core.Testing
0.1.1
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
<PackageReference Include="Hmz.Core.Testing" Version="0.1.1" />
<PackageVersion Include="Hmz.Core.Testing" Version="0.1.1" />
<PackageReference Include="Hmz.Core.Testing" />
paket add Hmz.Core.Testing --version 0.1.1
#r "nuget: Hmz.Core.Testing, 0.1.1"
#:package Hmz.Core.Testing@0.1.1
#addin nuget:?package=Hmz.Core.Testing&version=0.1.1
#tool nuget:?package=Hmz.Core.Testing&version=0.1.1
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:
- Assembly fixture — once for the test executable. The concrete fixture
derives from
PostgreSqlFunctionalTestFixtureBaseand is registered with[assembly: AssemblyFixture(...)]. Its constructor only defines the container. xUnit then calls itsInitializeAsync()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 sharedHttpClientand typed API client. - 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'sResetAsync(). For PostgreSQL this clears headers again, runs Respawn, reruns application/core seeding, recreates test data, and invokesAfterResetAsync().
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()orAfterResetAsync(); - replace it in
ConfigureTestServiceswith 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 | Versions 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. |
-
net10.0
- Microsoft.AspNetCore.Mvc.Testing (>= 10.0.12)
- Npgsql (>= 10.0.3)
- Respawn (>= 7.0.0)
- Testcontainers.PostgreSql (>= 4.15.0)
- xunit.v3.extensibility.core (>= 4.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.