Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created October 14, 2020 18:45
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/fa9e4c269962cbcbf2910fbaef4e7518 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/fa9e4c269962cbcbf2910fbaef4e7518 to your computer and use it in GitHub Desktop.
.NET Core xUnit test for testing the middleware using TestHost package
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Xunit;
namespace FirstWebApp.Tests
{
public class DummyCookieMiddlewareTests
{
[Fact]
public async Task GivenWebApp_WhenFirstRequestIsSentToWebApp_ThenDummyCookieIsAddedToResponse()
{
// Arrange
var memoryStream = new MemoryStream();
var testServer = await Setup.InitTestServer();
// Act
var resultContext = await testServer.SendAsync(context => {
context.Response.Body = memoryStream;
context.Request.Path = "/";
});
// Assert 1: if the next delegate was invoked
memoryStream.Position = 0;
string responseBody = new StreamReader(memoryStream).ReadToEnd();
Assert.Equal(Setup.ExpectedOutput, responseBody);
// Assert 2: if the cookie is added to the response
var setCookieHeaders = resultContext.Response.GetTypedHeaders().SetCookie;
var cookie = setCookieHeaders?.FirstOrDefault(x => x.Name == "DummyCookie");
Assert.True(Guid.TryParse(cookie.Value, out Guid result));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment