I want to test my MVC application, and I want to make fun of HttpContext. I use the Moq framework , and here is what I did to mock the HttpContext:
[SetUp]
public void Setup()
{
MyUser myUser = new MyUser();
myUser.Id = 1;
myUser.Name = "AutomatedUITestUser";
var fakeHttpSessionState =
new FakeHttpSessionState(new SessionStateItemCollection());
fakeHttpSessionState.Add("__CurrentUser__", myUser);
ControllerContext mockControllerContext = Mock.Of<ControllerContext>(ctx =>
ctx.HttpContext.User.Identity.Name == myUser.Name &&
ctx.HttpContext.User.Identity.IsAuthenticated == true &&
ctx.HttpContext.Session == fakeHttpSessionState &&
ctx.HttpContext.Request.AcceptTypes ==
new string[]{ "MyFormsAuthentication" } &&
ctx.HttpContext.Request.IsAuthenticated == true &&
ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
ctx.HttpContext.Response.ContentType == "application/xml");
_controller = new SomeController();
_controller.ControllerContext = mockControllerContext;
}
[Test]
public void Test_ControllerCanDoSomething()
{
}
Since my application uses Session to store user data and authentication information in almost all action methods, so I need to install HttpContextand inside it I need to install Sessionand put __CurrentUser__> inside the session so that the action methods have access to the fake registered user.
However, it is HttpContextnot installed and it is equal to zero. I searched a lot, and I could not find my answer. What could be wrong?
Update:
_controller.ControllerContext = new ControllerContext(
mockControllerContext.HttpContext, new RouteData(), _controller);