Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created October 11, 2020 19:07
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/edcfdbb15bdeee32e04eb03231df2e82 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/edcfdbb15bdeee32e04eb03231df2e82 to your computer and use it in GitHub Desktop.
Unit test for the dummy cookie middleware
public class DummyCookieMiddlewareTests
{
[Fact]
public void GivenWebApp_WhenFirstRequestIsSentToWebApp_ThenDummyCookieIsAddedToResponse()
{
const string expectedOutput = "Request handed over to next request delegate";
// Arrange
DefaultHttpContext defaultContext = new DefaultHttpContext();
defaultContext.Response.Body = new MemoryStream();
defaultContext.Request.Path = "/";
// Act
var middlewareInstance = new DummyCookieMiddleware(next: (innerHttpContext) =>
{
innerHttpContext.Response.WriteAsync(expectedOutput);
return Task.CompletedTask;
});
middlewareInstance.Invoke(defaultContext);
// Assert 1: if the next delegate was invoked
defaultContext.Response.Body.Seek(0, SeekOrigin.Begin);
var body = new StreamReader(defaultContext.Response.Body).ReadToEnd();
Assert.Equal(expectedOutput, body);
// Assert 2: if the cookie is added to the response
var setCookieHeaders = defaultContext.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