I am working on dot net core application. And, I want to write unit test to test that the ForwardHeaderOptions are setup correctly. Please see below the exact scenario.
public static class ProxyForwardedHeadersExtensions
{
public static IServiceCollection AddProxyForwardedHeaders(this IServiceCollection services)
{
services
.Configure<ForwardedHeadersOptions>(
options =>
{
options.ForwardLimit = null;
options.RequireHeaderSymmetry = false;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
options.ForwardedHeaders =
ForwardedHeaders.XForwardedHost
| ForwardedHeaders.XForwardedFor
| ForwardedHeaders.XForwardedProto;
});
return services;
}
}
In the above scenario, How can i test AddProxyForwardedHeaders method? I am not able to think of anything.
Thanks
I am trying to test with the following approach that creating web host and testclient. Calling AddProxyForwardedHeaders on services. But, I don't know how to verify if its working properly in unit test?
_builder = new HostBuilder()
.ConfigureWebHost(builder =>
builder
.UseTestServer()
.ConfigureServices(services => services.AddRouting().AddProxyForwardedHeaders())
.Configure(app =>
{
app.UseCustomMiddleware();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", context => Task.FromResult(new OkResult()));
});
app.UseProxyForwardedHeaders(sfName);
})
);
var host = _builder.Build();
await host.StartAsync();
var response = await host.GetTestClient().GetAsync("/");
Problem 2: I have one more method to test in same way like as below: public static void UseProxyForwardedHeaders(this IApplicationBuilder app, string serviceFabricServiceName) { app.UseForwardedHeaders();
app.Use(
(ctx, next) =>
{
if (string.IsNullOrWhiteSpace(serviceFabricServiceName))
{
return next();
}
ctx.Request.Scheme = "https";
var servicePathBase = serviceFabricServiceName;
ctx.Request.PathBase = new PathString(servicePathBase);
return next();
});
}
The problem is: How to unit test the context set here in this method. Please guide me. Thanks!
I tried to created a container and regist the options with the extension method then get the registed the options from the container and check the properties:
Result: