How do I mock a page request for a .net MVC page?
Using RhinoMocks:
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
httpContext.Expect( c => c.Request ).Return( httpRequest ).Repeat.Any();
... set up expectations on request...
var controller = new MyController();
controller.ControllerContext = new ControllerContext( httpContext,
new RouteData(),
controller );
...invoke action, check assertions...
httpContext.VerifyAllExpectations();
httpRequest.VerifyAllExpectations();
Using Moq:
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
request.Setup(x => x.ApplicationPath).Returns("/");
request.Setup(x => x.Url).Returns(new Uri("http://localhost/home"));
request.Setup(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
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