Skip to content

Instantly share code, notes, and snippets.

@bmorrisondev
Created March 6, 2020 14:52
Show Gist options
  • Save bmorrisondev/25cef7b5e46edaf08721f696f7cc1386 to your computer and use it in GitHub Desktop.
Save bmorrisondev/25cef7b5e46edaf08721f696f7cc1386 to your computer and use it in GitHub Desktop.
A simple method to mock out an HttpContext using NSubstitute for unit testing API Controllers in C#
using System;
using NSubstitute;
using Stage.Data;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Web;
namespace FakerTools
{
public static class HttpContextFaker
{
public static void FakeGenericPrincipalContext()
{
// You could also replace this with a custom identity as needed
var identity = Substitute.For<IIdentity>();
HttpContext.Current = new HttpContext(new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()));
HttpContext.Current.User = new GenericPrincipal(identity, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment