MemoryStream is a .NET stream implementation that keeps readable and writable data in memory. In middleware tests, it captures response content that would otherwise disappear into Stream.Null. section 36.1
Use a MemoryStream to inspect response content during an isolated middleware test:
- Create the MemoryStream and assign it to DefaultHttpContext.Response.Body. section 36.1
- Invoke the middleware, reposition the stream to its beginning, and read it with StreamReader. section 36.1
- Assert that the captured string contains the expected response, such as "pong". section 36.1
Listing 36.3 Unit testing StatusMiddleware when a matching Path is provided
[Fact]
public async Task ReturnsPongBodyContent()
{
var bodyStream = new MemoryStream(); #1
var context = new DefaultHttpContext(); #1
context.Response.Body = bodyStream; #1
context.Request.Path = "/ping"; #2
RequestDelegate next = (ctx) => Task.CompletedTask; #3
var middleware = new StatusMiddleware(next: next); #3
await middleware.Invoke(context); #4
string response; #5
bodyStream.Seek(0, SeekOrigin.Begin); #5
using (var stringReader = new StreamReader(bodyStream)) #5
{ #5
response = await stringReader.ReadToEndAsync(); #5
} #5
Assert.Equal("pong", response); #6
Assert.Equal("text/plain", context.Response.ContentType); #7
Assert.Equal(200, context.Response.StatusCode); #8
}
Shows a MemoryStream assigned to the response body before invoking middleware and reading the captured output. section 36.1
