I have a .net middleware that modifies the response and I’m trying to unit test it. I am able to successfully assert the status code and content type are correct, but when I attempt to assert the response body, it is an empty string even though a response body has been set.
I had no issues modifying or asserting the request body in another test. Is it possible to do the same for the response body?
Middleware:
using System.Net;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Web.API.Middleware
{
public class SampleMiddleware
{
private readonly RequestDelegate _next;
public SampleMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
bool success = true;
// do other stuff which has been removed...
context.Response.ContentType = MediaTypeNames.Text.Plain;
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await context.Response.WriteAsync("Bad request");
success = false;
if (success)
{
await _next(context);
}
}
}
}
Unit test:
using System.IO;
using System.Net;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Web.API.Middleware;
namespace Web.API.UnitTests
{
[TestClass]
public class SampleMiddlewareTest
{
[TestMethod]
public async Task BadRequestTest()
{
// Arrange
var expected = "Bad request";
var httpContext = new DefaultHttpContext();
var nextMock = new Mock<RequestDelegate>();
var middleware = new SampleMiddleware(nextMock.Object);
// Act
await middleware.InvokeAsync(httpContext);
// Assert
Assert.AreEqual((int)HttpStatusCode.BadRequest, httpContext.Response.StatusCode); // works
Assert.AreEqual(MediaTypeNames.Text.Plain, httpContext.Response.ContentType); // works
StreamReader reader = new StreamReader(httpContext.Response.Body);
var responseBody = reader.ReadToEnd();
Assert.AreEqual(expected, responseBody); // fails
}
}
}
Test result:
Assert.AreEqual failed. Expected:<Bad request>. Actual:<>.