Class AuthenticatedWebApplicationFactory<TEntryPoint>
- Namespace
- XBullet.EasyTesting.Hosting
- Assembly
- XBullet.EasyTesting.dll
An in-memory ASP.NET Core host whose default authentication scheme accepts per-request test users.
public class AuthenticatedWebApplicationFactory<TEntryPoint> : WebApplicationFactory<TEntryPoint>, IDisposable, IAsyncDisposable where TEntryPoint : class
Type Parameters
TEntryPointThe application entry-point type used by WebApplicationFactory<TEntryPoint> to locate and bootstrap the ASP.NET Core application.
- Inheritance
-
WebApplicationFactory<TEntryPoint>AuthenticatedWebApplicationFactory<TEntryPoint>
- Implements
- Derived
- Inherited Members
Constructors
AuthenticatedWebApplicationFactory()
Creates a factory with no additional test overrides.
public AuthenticatedWebApplicationFactory()
Properties
AuthenticationEvents
Gets authentication events captured from real handlers.
public TestAuthenticationEventRecorder AuthenticationEvents { get; }
Property Value
- TestAuthenticationEventRecorder
The factory-owned recorder shared with configured end-to-end authentication handlers. Do not dispose it. Scenario creation resets its mutable contents before and after each scope.
Methods
CaptureScenarioDiagnosticsAsync(TestScenarioScope<TEntryPoint>, CancellationToken)
Captures factory-specific state before a failed scenario is cleaned up.
protected virtual ValueTask<object?> CaptureScenarioDiagnosticsAsync(TestScenarioScope<TEntryPoint> scope, CancellationToken cancellationToken)
Parameters
scopeTestScenarioScope<TEntryPoint>The failed, factory-owned scenario scope. An override may inspect it but must not dispose it.
cancellationTokenCancellationTokenCancels diagnostic capture. The built-in failure path passes a non-cancelable token so diagnostics can be attempted even when the test token was canceled.
Returns
- ValueTask<object>
A serializable diagnostic value, or null when the factory has no additional state. Exceptions are converted to a diagnostic-capture failure record.
CleanupScenarioAsync(TestScenarioScope<TEntryPoint>, CancellationToken)
Cleans factory-specific state before the isolated scenario host is disposed.
protected virtual Task CleanupScenarioAsync(TestScenarioScope<TEntryPoint> scope, CancellationToken cancellationToken)
Parameters
scopeTestScenarioScope<TEntryPoint>The factory-owned scenario scope being cleaned up. An override may inspect it but must not dispose it.
cancellationTokenCancellationTokenCancels factory-specific cleanup when a caller supplies a cancelable token. Normal scope disposal passes a non-cancelable token so remaining cleanup operations can still run.
Returns
- Task
A task that completes when factory-specific cleanup has finished.
Client()
Starts a fluent test-client definition. Clients are anonymous until AsUser is called.
public TestClientBuilder<TEntryPoint> Client()
Returns
- TestClientBuilder<TEntryPoint>
A new mutable client builder. Clients produced by the builder are owned by the caller.
ConfigureScenarioEnvironment(TestScenarioEnvironmentBuilder)
Override to add external dependencies that are created for every scenario.
protected virtual void ConfigureScenarioEnvironment(TestScenarioEnvironmentBuilder environment)
Parameters
environmentTestScenarioEnvironmentBuilderThe mutable builder receiving environment-resource factories. The callback runs once per scenario before any resource factory is invoked. The factory owns the builder.
ConfigureServicesForScenario(IServiceCollection, TestScenarioContext)
Adds or replaces services that exist only for one scenario host.
protected virtual void ConfigureServicesForScenario(IServiceCollection services, TestScenarioContext context)
Parameters
servicesIServiceCollectionThe scenario host's service collection to mutate after environment resources have contributed services. An override must not retain or dispose it.
contextTestScenarioContextThe scenario context used to register scenario-owned cleanup and inspect the stable scenario identifier. The factory retains ownership of the context.
ConfigureServicesForTests(IServiceCollection)
Override to replace application services with test doubles.
protected virtual void ConfigureServicesForTests(IServiceCollection services)
Parameters
servicesIServiceCollectionThe host-owned service collection to mutate after XBullet authentication services are registered. An override must not retain or dispose it.
ConfigureTestAuthentication(TestAuthenticationSchemeBuilder)
Override to map Azure AD, API-key, or custom test profiles to application scheme names.
protected virtual void ConfigureTestAuthentication(TestAuthenticationSchemeBuilder authentication)
Parameters
authenticationTestAuthenticationSchemeBuilderThe mutable authentication builder used for this factory. An override may add or replace scheme mappings but must not retain or dispose the builder.
ConfigureTestConfiguration(IConfigurationBuilder)
Override to add in-memory configuration values to the test application.
protected virtual void ConfigureTestConfiguration(IConfigurationBuilder configuration)
Parameters
configurationIConfigurationBuilderThe host-owned configuration builder to mutate during host construction. An override must not retain or dispose it.
ConfigureTestHostSettings(IDictionary<string, string>)
Adds host settings that are visible while a minimal-hosting application is executing its
top-level startup code. This is appropriate for connection strings and other values read
immediately after WebApplication.CreateBuilder.
protected virtual void ConfigureTestHostSettings(IDictionary<string, string> settings)
Parameters
settingsIDictionary<string, string>A mutable, case-insensitive dictionary of host settings. An override may add or replace values but must not retain the dictionary after this method returns.
ConfigureWebHost(IWebHostBuilder)
Gives a fixture an opportunity to configure the application before it gets built.
protected override void ConfigureWebHost(IWebHostBuilder builder)
Parameters
builderIWebHostBuilderThe IWebHostBuilder for the application.
Create(Action<IServiceCollection>?, Action<IConfigurationBuilder>?, Action<TestAuthenticationSchemeBuilder>?)
Creates a factory with test service, configuration, and authentication callbacks.
public static AuthenticatedWebApplicationFactory<TEntryPoint> Create(Action<IServiceCollection>? configureServices = null, Action<IConfigurationBuilder>? configureConfiguration = null, Action<TestAuthenticationSchemeBuilder>? configureAuthentication = null)
Parameters
configureServicesAction<IServiceCollection>Configures the test host's service collection after XBullet authentication services are registered. When null, no additional service changes are applied. The callback runs for each host constructed from this factory, including derived scenario hosts, and can run concurrently when callers construct derived factories in parallel.
configureConfigurationAction<IConfigurationBuilder>Adds or replaces application configuration when the host is constructed. When null, no additional configuration sources are applied. The callback runs for each constructed host, can run concurrently for parallel derived hosts, and must not retain or dispose the supplied builder.
configureAuthenticationAction<TestAuthenticationSchemeBuilder>Configures simulated and end-to-end authentication schemes before the host is constructed. When null, the default simulated test scheme is used. The callback runs once with a mutable authentication builder.
Returns
- AuthenticatedWebApplicationFactory<TEntryPoint>
A new application factory owned by the caller. Dispose it after all clients and scenario scopes created from it have been disposed.
CreateAnonymousClient(WebApplicationFactoryClientOptions?)
Creates a client that sends requests without a test identity.
public HttpClient CreateAnonymousClient(WebApplicationFactoryClientOptions? options = null)
Parameters
optionsWebApplicationFactoryClientOptionsClient options to apply. When null, the factory's default client options are used. The options object is read but not owned or mutated.
Returns
- HttpClient
A new anonymous client connected to the in-memory server. The caller owns and must dispose the client.
CreateAuthenticatedClient(TestUser?, WebApplicationFactoryClientOptions?)
Creates a client whose requests use the supplied test identity.
public HttpClient CreateAuthenticatedClient(TestUser? user = null, WebApplicationFactoryClientOptions? options = null)
Parameters
userTestUserThe simulated identity sent with requests. When null, a default authenticated test user is created. The supplied user is read but not owned or mutated.
optionsWebApplicationFactoryClientOptionsClient options to apply. When null, the factory's default client options are used. The options object is read but not owned or mutated.
Returns
- HttpClient
A new authenticated client connected to the in-memory server. The caller owns and must dispose the client.
CreateTestScenarioScopeAsync(Action<TestScenarioScopeBuilder>?, CancellationToken)
Creates an isolated per-test scope. Shared registered resources are protected for the complete lifetime of the scope and reset before it starts and after it is disposed.
public Task<TestScenarioScope<TEntryPoint>> CreateTestScenarioScopeAsync(Action<TestScenarioScopeBuilder>? configure = null, CancellationToken cancellationToken = default)
Parameters
configureAction<TestScenarioScopeBuilder>Configures service, application-configuration, and environment-resource overrides for this scope. When null, only factory-level configuration is used. The callback runs once, synchronously, before the method waits for another scope to finish, so concurrent scope-creation calls can invoke it concurrently.
cancellationTokenCancellationTokenCancels waiting for exclusive access, shared-resource reset, environment-resource startup, host creation, or scenario initialization. Resources created before cancellation are still cleaned up. The default token does not request cancellation.
Returns
- Task<TestScenarioScope<TEntryPoint>>
A caller-owned scope containing the isolated host and scenario resources. The caller must asynchronously dispose the scope to release the factory for the next scenario.
CreateWithHostSettings(Action<IDictionary<string, string>>, Action<IServiceCollection>?, Action<IConfigurationBuilder>?, Action<TestAuthenticationSchemeBuilder>?)
Creates a factory with settings available to minimal-hosting startup code.
public static AuthenticatedWebApplicationFactory<TEntryPoint> CreateWithHostSettings(Action<IDictionary<string, string>> configureHostSettings, Action<IServiceCollection>? configureServices = null, Action<IConfigurationBuilder>? configureConfiguration = null, Action<TestAuthenticationSchemeBuilder>? configureAuthentication = null)
Parameters
configureHostSettingsAction<IDictionary<string, string>>Adds or replaces values in a mutable, case-insensitive settings dictionary before minimal-hosting startup code runs. The callback runs for each constructed host, can run concurrently for parallel derived hosts, and must not retain the dictionary.
configureServicesAction<IServiceCollection>Configures the test host's service collection after XBullet authentication services are registered. When null, no additional service changes are applied. The callback runs for each constructed host and can run concurrently for parallel derived hosts.
configureConfigurationAction<IConfigurationBuilder>Adds or replaces application configuration when the host is constructed. When null, no additional configuration sources are applied. The callback runs for each constructed host and can run concurrently for parallel derived hosts.
configureAuthenticationAction<TestAuthenticationSchemeBuilder>Configures simulated and end-to-end authentication schemes. When null, the default simulated test scheme is used.
Returns
- AuthenticatedWebApplicationFactory<TEntryPoint>
A new application factory owned by the caller. Dispose it after all clients and scenario scopes created from it have been disposed.
Dispose(bool)
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
protected override void Dispose(bool disposing)
Parameters
disposingbooltrue to release both managed and unmanaged resources; false to release only unmanaged resources.
InitializeScenarioAsync(TestScenarioScope<TEntryPoint>, CancellationToken)
Initializes state after the isolated scenario host has started.
protected virtual Task InitializeScenarioAsync(TestScenarioScope<TEntryPoint> scope, CancellationToken cancellationToken)
Parameters
scopeTestScenarioScope<TEntryPoint>The newly started, factory-owned scenario scope. An override may use it but must not dispose it.
cancellationTokenCancellationTokenCancels scenario initialization. When cancellation or another failure occurs, the scope is still cleaned up. The token is the one supplied to scope creation.
Returns
- Task
A task that completes when scenario-specific initialization has finished.
JwtAuthority(string?)
Gets a configured local JWT authority, optionally by authentication scheme.
public TestJwtAuthority JwtAuthority(string? authenticationScheme = null)
Parameters
authenticationSchemestringThe exact registered authentication scheme to select. When null, the default local JWT authority is returned.
Returns
- TestJwtAuthority
The factory-owned authority for the selected scheme. Do not dispose it.
RegisterScenarioResource(string, Action, Func<object?>)
Registers mutable state that is automatically reset around every scenario and captured when one fails. Call this from a derived factory constructor.
protected void RegisterScenarioResource(string name, Action reset, Func<object?> captureDiagnostics)
Parameters
namestringThe non-empty, case-insensitively unique name used as the diagnostic-data key.
resetActionThe callback invoked before and after every scenario to clear shared mutable state. Calls are sequential and never concurrent for a single factory. The factory does not own captured objects referenced by the callback.
captureDiagnosticsFunc<object>The callback invoked once when a scenario fails, before cleanup and reset. It returns a serializable diagnostic value or null. Exceptions are recorded as diagnostic-capture failures instead of replacing the original test failure.
RegisterScenarioResource(string, ITestScenarioResource)
Registers a resettable resource that participates in every scenario scope. Call this from a derived factory constructor.
protected void RegisterScenarioResource(string name, ITestScenarioResource resource)
Parameters
namestringThe non-empty, case-insensitively unique name used as the diagnostic-data key.
resourceITestScenarioResourceThe resource whose reset and diagnostic callbacks participate in every scenario. The factory does not take ownership or dispose the resource.
RunInTestScenarioScopeAsync(Func<TestScenarioScope<TEntryPoint>, CancellationToken, Task>, Action<TestScenarioScopeBuilder>?, CancellationToken)
Runs a test inside an isolated scenario scope, captures diagnostics on failure, and always cleans up.
public Task RunInTestScenarioScopeAsync(Func<TestScenarioScope<TEntryPoint>, CancellationToken, Task> test, Action<TestScenarioScopeBuilder>? configure = null, CancellationToken cancellationToken = default)
Parameters
testFunc<TestScenarioScope<TEntryPoint>, CancellationToken, Task>The asynchronous test callback invoked once with the newly created scope and
cancellationToken. A single factory never runs two test callbacks concurrently.configureAction<TestScenarioScopeBuilder>Configures overrides for the new scope. When null, only factory-level configuration is used. The callback runs once before scope creation begins and can run concurrently across simultaneous calls.
cancellationTokenCancellationTokenCancels scope creation and the test callback. Failure diagnostics and cleanup run with a non-cancelable token so cancellation cannot leave factory-owned state uncleared. The default token does not request cancellation.
Returns
- Task
A task that completes after the test callback and all scope cleanup complete.
RunInTestScenarioScopeAsync<TResult>(Func<TestScenarioScope<TEntryPoint>, CancellationToken, Task<TResult>>, Action<TestScenarioScopeBuilder>?, CancellationToken)
Runs a test function inside an isolated scenario scope, captures diagnostics on failure, and always cleans up.
public Task<TResult> RunInTestScenarioScopeAsync<TResult>(Func<TestScenarioScope<TEntryPoint>, CancellationToken, Task<TResult>> test, Action<TestScenarioScopeBuilder>? configure = null, CancellationToken cancellationToken = default)
Parameters
testFunc<TestScenarioScope<TEntryPoint>, CancellationToken, Task<TResult>>The asynchronous test callback invoked once with the newly created scope and
cancellationToken. A single factory never runs two test callbacks concurrently.configureAction<TestScenarioScopeBuilder>Configures overrides for the new scope. When null, only factory-level configuration is used. The callback runs once before scope creation begins and can run concurrently across simultaneous calls.
cancellationTokenCancellationTokenCancels scope creation and the test callback. Failure diagnostics and cleanup run with a non-cancelable token so cancellation cannot leave factory-owned state uncleared. The default token does not request cancellation.
Returns
- Task<TResult>
The value produced by
testafter the scope has been cleaned up.
Type Parameters
TResultThe value returned by the asynchronous test callback.
Scenario()
Starts a composable arrange, client, and HTTP request scenario.
public TestScenarioBuilder<TEntryPoint> Scenario()
Returns
- TestScenarioBuilder<TEntryPoint>
A new mutable scenario builder associated with this factory.