Test support API services
Overview
Contains support for unit tests and integration tests of domain logic, API services, and API connectors.
Install
- ASOL.Core.QA.TestSupport.ApiServices
Authentication + Authorization Mock
To support mocking of authentication and authorization, the following classes were introduced: TestingAuthenticationHandler, TestingAuthenticationHeader, and TestingAuthorizationTokenProvider.
When using the WebApplicationFactory for creating an integration test, the following technique can be used.
In your CustomWebApplicationFactory, change the default authentication scheme set by the entry point to a Testing scheme and choose the TestingAuthenticationHandler as its handler:
public sealed class CustomWebApplicationFactory<TEntrypoint> : WebApplicationFactory<TEntrypoint>
where TEntrypoint : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication(options =>
{
options.DefaultScheme = "Testing";
options.DefaultAuthenticateScheme = "Testing";
options.DefaultChallengeScheme = "Testing";
options.DefaultSignInScheme = "Testing";
})
.AddScheme<AuthenticationSchemeOptions, TestingAuthenticationHandler>(
"Testing", null);
});
}
}
Then, when calling any API, add an authentication header to each call. This header can be created from a ClaimsPrincipal instance with the help of TestingAuthenticationHeader class:
ClaimsPrincipal user = ClaimsPrincipalBuilder.CreateUserPrincipal(
userId: userId,
tenantId: tenantId,
userName: "test-user-name")
.AddAuthenticateType("Platform")
.Build();
string authenticationHeaderValue = TestingAuthenticationHeader.Encode(user);
or by ClaimsPrincipal extension method:
string authenticationHeaderValue = user.EncodeToAuthenticationHeader();
Use Bearer as the authentication scheme value or TestingAuthenticationHeader.Scheme.
If an inheritor of the SecuredApiClientBase class is used for HTTP request creation:
public sealed class CustomClient
(
IOptions<CustomClientOptions> options,
ILogger<CustomClient> logger,
IConnectorTokenProvider tokenProvider,
IEnumerable<IRequestHeaderProvider> headerProviders,
HttpClient? baseClient = null,
bool manageBaseClient = false
) :
SecuredApiClientBase<CustomClientOptions, IConnectorTokenProvider>(
options.Value,
logger,
tokenProvider,
headerProviders,
baseClient,
manageBaseClient)
{
}
an instance of TestingAuthorizationTokenProvider may be used to facilitate including the authentication header in the request:
ClaimsPrincipal user = ...;
var client = new CustomClient(
Options.Create(new CustomClientOptions()),
NullLogger<CustomClient>.Instance,
new TestingAuthorizationTokenProvider(user),
[]);