Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock the HttpContext in ASP.NET MVC using Moq?

[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.

like image 468
Geo Avatar asked Sep 21 '09 00:09

Geo


People also ask

Can we mock HttpContext?

HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated ( HttpContextWrapper is used as an adapter between them). Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity .

What can be mocked with MOQ?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.

What is HttpContext MVC?

HttpContext is a type which has a static Current property that you're using to get the current context. There isn't a System. Web. Mvc.


2 Answers

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

 controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller ); 
like image 181
tvanfosson Avatar answered Sep 18 '22 13:09

tvanfosson


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

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", ""); StringWriter stringWriter = new StringWriter(); HttpResponse httpResponse = new HttpResponse(stringWriter); HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse); 
like image 28
0100110010101 Avatar answered Sep 20 '22 13:09

0100110010101