3
votes

I am attempting to mock a controller's Session variable using Moq. What I keep running into is that the Session is visible from the test, but null inside the actual controller.

Test code:

[TestMethod]
public void SessionTest()
{
    var controller = new BaseController();
    var controllerContext = new Mock<ControllerContext>();
    controllerContext.Setup(cc => cc.HttpContext.Session["user"]).Returns(new User());
    controller.ControllerContext = controllerContext.Object;

    User currentUser = controller.CurrentUser; //fails (throws NullReferenceException)
    User currentUser = (User)controller.Session["test"]; //works
}

Controller code:

public User CurrentUser
{
    get
    {
        return (User)Session["user"]; //HttpContext is null at this point
    }
}

The code above follows the most common pattern I've seen (several SO postings, the MVC 2 in Action Ch. 7 example, etc.), but still doesn't work. Inside the controller, the ControllerContext is null, as is the HttpContext. What am I doing wrong?

1
I have just created simple solution repeating you problem and I cannot reproduce it. What version of Moq you are using? - Restuta

1 Answers

1
votes

It must have been a configuration issue caused by adding a unit test project to an already-existing project, because I just created a new MVC 3 project, checked the 'Create Unit Test Project', added all of my controllers, models, etc. from the old project to the new one, and it's working just fine.