|
| 1 | +## About |
| 2 | + |
| 3 | +`Microsoft.AspNetCore.TestHost` provides an ASP.NET Core web server for testing middleware in isolation. |
| 4 | + |
| 5 | +## Key Features |
| 6 | + |
| 7 | +* Instantiate an app pipeline containing only the components that you need to test |
| 8 | +* Send custom requests to verify middleware behavior |
| 9 | + |
| 10 | +## How to Use |
| 11 | + |
| 12 | +To use `Microsoft.AspNetCore.TestHost`, follow these steps: |
| 13 | + |
| 14 | +### Installation |
| 15 | + |
| 16 | +```shell |
| 17 | +dotnet add package Microsoft.AspNetCore.TestHost |
| 18 | +``` |
| 19 | + |
| 20 | +### Usage |
| 21 | + |
| 22 | +To set up the `TestServer`, configure it in your test project. Here's an example: |
| 23 | + |
| 24 | +```csharp |
| 25 | +[Fact] |
| 26 | +public async Task MiddlewareTest_ReturnsNotFoundForRequest() |
| 27 | +{ |
| 28 | + // Build and start a host that uses TestServer |
| 29 | + using var host = await new HostBuilder() |
| 30 | + .ConfigureWebHost(builder => |
| 31 | + { |
| 32 | + builder.UseTestServer() |
| 33 | + .ConfigureServices(services => |
| 34 | + { |
| 35 | + // Add any required services that the middleware uses |
| 36 | + services.AddMyServices(); |
| 37 | + }) |
| 38 | + .Configure(app => |
| 39 | + { |
| 40 | + // Configure the processing pipeline to use the middleware |
| 41 | + // for the test |
| 42 | + app.UseMiddleware<MyMiddleware>(); |
| 43 | + }); |
| 44 | + }) |
| 45 | + .StartAsync(); |
| 46 | + |
| 47 | + var response = await host.GetTestClient().GetAsync("/"); |
| 48 | + |
| 49 | + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +## Main Types |
| 54 | + |
| 55 | +The main types provided by this package are: |
| 56 | + |
| 57 | +* `TestServer`: An `IServer` implementation for executing tests |
| 58 | +* `TestServerOptions`: Provides options for configuring a `TestServer` |
| 59 | + |
| 60 | +## Additional Documentation |
| 61 | + |
| 62 | +For additional documentation and examples, refer to the [official documentation](https://learn.microsoft.com/aspnet/core/test/middleware) for testing middleware in ASP.NET Core. |
| 63 | + |
| 64 | +## Feedback & Contributing |
| 65 | + |
| 66 | +`Microsoft.AspNetCore.TestHost` is released as open-source under the [MIT license](https://licenses.nuget.org/MIT). Bug reports and contributions are welcome at [the GitHub repository](https://github.com/dotnet/aspnetcore). |
0 commit comments