MinimalWebHostTestFactory Class
Definition
- Namespace
- Codebelt.Extensions.Xunit.Hosting.AspNetCore
- Assemblies
- Codebelt.Extensions.Xunit.Hosting.AspNetCore.dll
Provides a set of static methods for ASP.NET Core (including, but not limited to MVC, Razor and related) unit testing (minimal style).
public static class MinimalWebHostTestFactory
- Inheritance
-
MinimalWebHostTestFactory
Examples
Use MinimalWebHostTestFactory when a test needs the modern IHostApplicationBuilder configuration model and a small in-memory request pipeline. The example supplies a health state through dependency injection, serves it from middleware, and reads the response returned by RunAsync.
using System.Threading.Tasks;
using Codebelt.Extensions.Xunit.Hosting.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace HealthEndpoint.Tests;
public sealed class MinimalWebHostTestFactoryExample
{
public async Task<string> ReadHealthStateAsync()
{
using var response = await MinimalWebHostTestFactory.RunAsync(
services => services.AddSingleton(new HealthState("healthy")),
app => app.Run(context =>
{
var health = context.RequestServices.GetRequiredService<HealthState>();
return context.Response.WriteAsync(health.Value);
})).ConfigureAwait(false);
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
public sealed record HealthState(string Value);
Methods
| Name | Description |
|---|---|
| Create(Action<IServiceCollection>, Action<IApplicationBuilder>, Action<IHostApplicationBuilder>, IWebMinimalHostFixture) | Creates and returns an IWebHostTest implementation. |
| CreateWithHostBuilderContext(Action<HostBuilderContext, IServiceCollection>, Action<HostBuilderContext, IApplicationBuilder>, Action<IHostApplicationBuilder>, IWebMinimalHostFixture) | Creates and returns an IWebHostTest implementation. |
| RunAsync(Action<IServiceCollection>, Action<IApplicationBuilder>, Action<IHostApplicationBuilder>, Func<HttpClient, Task<HttpResponseMessage>>, IWebMinimalHostFixture) | Runs a middleware and returns an HttpClient for making HTTP requests to the test server. |
| RunWithHostBuilderContextAsync(Action<HostBuilderContext, IServiceCollection>, Action<HostBuilderContext, IApplicationBuilder>, Action<IHostApplicationBuilder>, Func<HttpClient, Task<HttpResponseMessage>>, IWebMinimalHostFixture) | Runs a filter/middleware test. |