38

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

2 Answers 2

63

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Do guys also have a snippet for doing the same thing but uses microsft fakes/test and not any other 3rd party testing framework?
4

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;           

1 Comment

This solution is working for me in the ASP.Net MVC application when creating a Test Case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.