How to mock an HttpContext (ControllerContext) in a Moq structure and have a session

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; //this line is not working
    //when I see _controller.ControllerContext in watch, it get me 
    //_controller.ControllerContext threw an exception of type System.ArgumentException
}

[Test]
public void Test_ControllerCanDoSomething()
{
    // testing an action of the controller
    // The problem is, here, System.Web.HttpContext.Current is null
}

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);
+4
1

: Mocking Asp.net-mvc

, , .

.

var request = new Mock<HttpRequestBase>();

.. ( ).

+3

Source: https://habr.com/ru/post/1530255/


All Articles