Created
March 6, 2020 14:52
-
-
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#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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