From e8a7585f19647d6d5a46f1f0eea90e8db2b1ed92 Mon Sep 17 00:00:00 2001 From: Luke Latham <1622880+guardrex@users.noreply.github.com> Date: Wed, 6 May 2020 14:10:08 -0500 Subject: [PATCH] Test middleware topic (#18114) --- aspnetcore/fundamentals/middleware/index.md | 4 +- aspnetcore/fundamentals/middleware/write.md | 3 +- aspnetcore/test/middleware.md | 105 ++++++++++++++++++ .../3.x/false-failure-check.cs | 26 +++++ .../samples_snapshot/3.x/final-test.cs | 23 ++++ .../samples_snapshot/3.x/request.cs | 23 ++++ .../middleware/samples_snapshot/3.x/setup.cs | 21 ++++ aspnetcore/toc.yml | 2 + 8 files changed, 205 insertions(+), 2 deletions(-) create mode 100644 aspnetcore/test/middleware.md create mode 100644 aspnetcore/test/middleware/samples_snapshot/3.x/false-failure-check.cs create mode 100644 aspnetcore/test/middleware/samples_snapshot/3.x/final-test.cs create mode 100644 aspnetcore/test/middleware/samples_snapshot/3.x/request.cs create mode 100644 aspnetcore/test/middleware/samples_snapshot/3.x/setup.cs diff --git a/aspnetcore/fundamentals/middleware/index.md b/aspnetcore/fundamentals/middleware/index.md index 6e0cd02f32..e1d599e9d7 100644 --- a/aspnetcore/fundamentals/middleware/index.md +++ b/aspnetcore/fundamentals/middleware/index.md @@ -5,7 +5,7 @@ description: Learn about ASP.NET Core middleware and the request pipeline. monikerRange: '>= aspnetcore-2.1' ms.author: riande ms.custom: mvc -ms.date: 04/06/2020 +ms.date: 5/6/2020 no-loc: [Blazor, "Identity", "Let's Encrypt", Razor, SignalR] uid: fundamentals/middleware/index --- @@ -256,6 +256,7 @@ ASP.NET Core ships with the following middleware components. The *Order* column ## Additional resources * +* * * * @@ -459,6 +460,7 @@ ASP.NET Core ships with the following middleware components. The *Order* column ## Additional resources * +* * * * diff --git a/aspnetcore/fundamentals/middleware/write.md b/aspnetcore/fundamentals/middleware/write.md index 12122c4232..92f5570c23 100644 --- a/aspnetcore/fundamentals/middleware/write.md +++ b/aspnetcore/fundamentals/middleware/write.md @@ -5,7 +5,7 @@ description: Learn how to write custom ASP.NET Core middleware. monikerRange: '>= aspnetcore-2.1' ms.author: riande ms.custom: mvc -ms.date: 08/22/2019 +ms.date: 5/6/2020 no-loc: [Blazor, "Identity", "Let's Encrypt", Razor, SignalR] uid: fundamentals/middleware/write --- @@ -80,6 +80,7 @@ The following code calls the middleware from `Startup.Configure`: ## Additional resources * +* * * * diff --git a/aspnetcore/test/middleware.md b/aspnetcore/test/middleware.md new file mode 100644 index 0000000000..b9520df1e6 --- /dev/null +++ b/aspnetcore/test/middleware.md @@ -0,0 +1,105 @@ +--- +title: Test ASP.NET Core middleware +author: tratcher +description: Learn how to test ASP.NET Core middleware with TestServer. +ms.author: riande +ms.custom: mvc +ms.date: 5/6/2019 +no-loc: [Blazor, "Identity", "Let's Encrypt", Razor, SignalR] +uid: test/middleware +--- +# Test ASP.NET Core middleware + +By [Chris Ross](https://github.com/Tratcher) + +Middleware can be tested in isolation with . It allows you to: + +* Instantiate an app pipeline containing only the components that you need to test. +* Send custom requests to verify middleware behavior. + +Advantages: + +* Requests are sent in-memory rather than being serialized over the network. +* This avoids additional concerns, such as port management and HTTPS certificates. +* Exceptions in the middleware can flow directly back to the calling test. +* It's possible to customize server data structures, such as , directly in the test. + +## Set up the TestServer + +In the test project, create a test: + +* Build and start a host that uses . +* Add any required services that the middleware uses. +* Configure the processing pipeline to use the middleware for the test. + +[!code-csharp[](middleware/samples_snapshot/3.x/setup.cs?highlight=4-18)] + +## Send requests with HttpClient +Send a request using : + +[!code-csharp[](middleware/samples_snapshot/3.x/request.cs?highlight=20)] + +Assert the result. First, make an assertion the opposite of the result that you expect. An initial run with a false positive assertion confirms that the test fails when the middleware is performing correctly. Run the test and confirm that the test fails. + +In the following example, the middleware should return a 404 status code (*Not Found*) when the root endpoint is requested. Make the first test run with `Assert.NotEqual( ... );`, which should fail: + +[!code-csharp[](middleware/samples_snapshot/3.x/false-failure-check.cs?highlight=22)] + +Change the assertion to test the middleware under normal operating conditions. The final test uses `Assert.Equal( ... );`. Run the test again to confirm that it passes. + +[!code-csharp[](middleware/samples_snapshot/3.x/final-test.cs?highlight=22)] + +## Send requests with HttpContext + +A test app can also send a request using [SendAsync(Action\, CancellationToken)](xref:Microsoft.AspNetCore.TestHost.TestServer.SendAsync%2A). In the following example, several checks are made when `https://example.com/A/Path/?and=query` is processed by the middleware: + +```csharp +[Fact] +public async Task TestMiddleware_ExpectedResponse() +{ + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddMyServices(); + }) + .Configure(app => + { + app.UseMiddleware(); + }); + }) + .StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://example.com/A/Path/"); + + var context = await server.SendAsync(c => + { + c.Request.Method = HttpMethods.Post; + c.Request.Path = "/and/file.txt"; + c.Request.QueryString = new QueryString("?and=query"); + }); + + Assert.True(context.RequestAborted.CanBeCanceled); + Assert.Equal(HttpProtocol.Http11, context.Request.Protocol); + Assert.Equal("POST", context.Request.Method); + Assert.Equal("https", context.Request.Scheme); + Assert.Equal("example.com", context.Request.Host.Value); + Assert.Equal("/A/Path", context.Request.PathBase.Value); + Assert.Equal("/and/file.txt", context.Request.Path.Value); + Assert.Equal("?and=query", context.Request.QueryString.Value); + Assert.NotNull(context.Request.Body); + Assert.NotNull(context.Request.Headers); + Assert.NotNull(context.Response.Headers); + Assert.NotNull(context.Response.Body); + Assert.Equal(404, context.Response.StatusCode); + Assert.Null(context.Features.Get().ReasonPhrase); +} +``` + + permits direct configuration of an object rather than using the abstractions. Use to manipulate structures only available on the server, such as [HttpContext.Items](xref:Microsoft.AspNetCore.Http.HttpContext.Items) or [HttpContext.Features](xref:Microsoft.AspNetCore.Http.HttpContext.Features). + +As with the earlier example that tested for a *404 - Not Found* response, check the opposite for each `Assert` statement in the preceding test. The check confirms that the test fails correctly when the middleware is operating normally. After you've confirmed that the false positive test works, set the final `Assert` statements for the expected conditions and values of the test. Run it again to confirm that the test passes. diff --git a/aspnetcore/test/middleware/samples_snapshot/3.x/false-failure-check.cs b/aspnetcore/test/middleware/samples_snapshot/3.x/false-failure-check.cs new file mode 100644 index 0000000000..6b68511dce --- /dev/null +++ b/aspnetcore/test/middleware/samples_snapshot/3.x/false-failure-check.cs @@ -0,0 +1,26 @@ +[Fact] +public async Task MiddlewareTest_ReturnsNotFoundForRequest() +{ + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddMyServices(); + }) + .Configure(app => + { + app.UseMiddleware(); + }); + }) + .StartAsync(); + + var testServer = host.GetTestServer(); + + var testClient = testServer.CreateClient(); + var response = await testClient.GetAsync("/"); + + Assert.NotEqual(HttpStatusCode.NotFound, response.StatusCode); +} diff --git a/aspnetcore/test/middleware/samples_snapshot/3.x/final-test.cs b/aspnetcore/test/middleware/samples_snapshot/3.x/final-test.cs new file mode 100644 index 0000000000..7d61aa8c28 --- /dev/null +++ b/aspnetcore/test/middleware/samples_snapshot/3.x/final-test.cs @@ -0,0 +1,23 @@ +[Fact] +public async Task MiddlewareTest_ReturnsNotFoundForRequest() +{ + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddMyServices(); + }) + .Configure(app => + { + app.UseMiddleware(); + }); + }) + .StartAsync(); + + var response = await host.GetTestServer().CreateClient().GetAsync("/"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); +} diff --git a/aspnetcore/test/middleware/samples_snapshot/3.x/request.cs b/aspnetcore/test/middleware/samples_snapshot/3.x/request.cs new file mode 100644 index 0000000000..95205f7280 --- /dev/null +++ b/aspnetcore/test/middleware/samples_snapshot/3.x/request.cs @@ -0,0 +1,23 @@ +[Fact] +public async Task MiddlewareTest_ReturnsNotFoundForRequest() +{ + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddMyServices(); + }) + .Configure(app => + { + app.UseMiddleware(); + }); + }) + .StartAsync(); + + var response = await host.GetTestServer().CreateClient().GetAsync("/"); + + ... +} diff --git a/aspnetcore/test/middleware/samples_snapshot/3.x/setup.cs b/aspnetcore/test/middleware/samples_snapshot/3.x/setup.cs new file mode 100644 index 0000000000..d47023b80e --- /dev/null +++ b/aspnetcore/test/middleware/samples_snapshot/3.x/setup.cs @@ -0,0 +1,21 @@ +[Fact] +public async Task MiddlewareTest_ReturnsNotFoundForRequest() +{ + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddMyServices(); + }) + .Configure(app => + { + app.UseMiddleware(); + }); + }) + .StartAsync(); + + ... +} diff --git a/aspnetcore/toc.yml b/aspnetcore/toc.yml index 74b18ea7cf..8d4a2f18f2 100644 --- a/aspnetcore/toc.yml +++ b/aspnetcore/toc.yml @@ -665,6 +665,8 @@ uid: test/razor-pages-tests - name: Test controllers uid: mvc/controllers/testing + - name: Test middleware + uid: test/middleware - name: Remote debugging href: /visualstudio/debugger/remote-debugging-azure - name: Snapshot debugging