Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing in asp.net MVC, how do I mock a page request?

How do I mock a page request for a .net MVC page?

like image 694
Blankman Avatar asked Apr 21 '09 19:04

Blankman


2 Answers

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();
like image 101
tvanfosson Avatar answered Oct 15 '22 10:10

tvanfosson


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);
like image 21
eu-ge-ne Avatar answered Oct 15 '22 10:10

eu-ge-ne