Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Test will fail because it couldn't find
HttpContext
So how can I mock
HttpContext.Current.User.Identity.Name
I'm using Moq for Mocking
you can initialize your controller with fake context with fake principal as shown below
var fakeHttpContext = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);
fakeHttpContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);
_requestController = new RequestController();
//Set your controller ControllerContext with fake context
_requestController.ControllerContext = controllerContext.Object;
–
To do it using Microsoft tests only (no 3rd party frameworks), you can do as below:
public class MockHttpContextBase : HttpContextBase
public override IPrincipal User { get; set; }
And then...
var userToTest = "User";
string[] roles = null;
var fakeIdentity = new GenericIdentity(userToTest);
var principal = new GenericPrincipal(fakeIdentity, roles);
var fakeHttpContext = new MockHttpContextBase { User = principal };
var controllerContext = new ControllerContext
HttpContext = fakeHttpContext
// This is the controller that we wish to test:
_requestController = new RequestController();
// Now set the controller ControllerContext with fake context
_requestController.ControllerContext = controllerContext;
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.