I have code in the controller which consumes HttpContext
public ActionResult Index() { var currentUser=HttpContext.User.Identity.Name; ...... }
While trying to write test using NUnit like this
[Test] public void CanDisplayRequest() { //Act var result= (ViewResult)_requestController.Index(); //Assert Assert.IsInstanceOf<OrderRequest>(resut.Model); }
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With