[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.
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 .
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.
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.
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 );
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With