Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created October 14, 2020 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/f2ddb3ff3baf7b2e5e9e65030db933e6 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/f2ddb3ff3baf7b2e5e9e65030db933e6 to your computer and use it in GitHub Desktop.
.NET Core unit test for testing middleware using TestHost package
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using FirstWebApp;
namespace FirstWebApp.Tests
{
public class Setup
{
public const string ExpectedOutput = "Request handed over to next request delegate";
public static async Task<TestServer> InitTestServer()
{
var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.UseStartup<TestStartup>();
})
.StartAsync();
return host.GetTestServer();
}
}
public class TestStartup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDummyCookieMiddleware();
app.Run(async context =>
{
await context.Response.WriteAsync(Setup.ExpectedOutput);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment