views:

1260

answers:

3
    [TestMethod]
    public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        context
            .Setup(c => c.Request)
            .Returns(request.Object);
        HomeController controller = new HomeController();

        controller.HttpContext = context; //Here I am getting an error (read only).

        ...
     }

my base controller has an overrride of the Initialize that get's this requestContext. I am trying to pass this along but I am not doing something right.

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

Where can I get more information on mocking my requestcontext and httpcontext using moq. I am trying to mock cookies and the general context.

+4  A: 

HttpContext is read-only, but it is actually derived from the ControllerContext, which you can set.

 controller.ControllerContext = new ControllerContext( httpContext, new RouteData(), controller );
tvanfosson
+6  A: 

Try checking Scott Hanselman's Mock example. That could lead you in the right direction.

Hope this helps!

mallows98
A: 

Create a request, response and put them both to HttpContext:

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponce = new HttpResponse(stringWriter);
HttpContext httpConextMock = new HttpContext(httpRequest, httpResponce);
ifesdjeen
The question is about the *Base classes, ie HttpRequestBase, not HttpRequest - not sure why both are needed myself and even more annoying that they are "sealed". No way to set LogonUserIdentity :(
Chris Kimpton
If they're marshalled my reference, it's still possible via remoting, so it shouldn't be a problem.
ifesdjeen