views:

214

answers:

3

I'm currently testing my application and am stuck on trying to figure out how to create a custom fake URL referrer. I've tried to hard code it, but am getting an error that it is read-only. Here is what I've tried so far:

fakeController.HttpContext.Request.UrlReferrer.AbsolutePath = "http://www.yahoo.com";

as well as,

fakeController.Request.UrlReferrer = "http://www.yahoo.com";

I've searched the web for some ideas on how to create a fake/mock URL referrer for my fake controller, but have had no luck. Any suggestions are welcome.

Note: I'm using Visual Studios built-in unit testing facilities.

UPDATE:

Thank you all for your suggestions so far, I would be more than willing to use any other unit testing system outside of Visual Studio, unfortunately here at my work we are only allowed to use Visual Studio's built-in system, so I gotta work with what I've got. Thank you though, it's good to know these options are out there.

A: 

I Recommend changing to a Mock Framework such as NMock or Rhino Mock which allows you to create those, and returns an specific value for a given call such as the get method in that property.

jpabluz
+2  A: 

Create a mock request for the HttpContext, then set up an expectation on the Request that returns a Uri. Example using RhinoMocks.

 var context = MockRepository.GenerateMock<HttpContextBase>();
 var request = MockRepository.GenerateMock<HttpRequestBase>();
 request.Expect( r => r.UrlReferrer ).Return( new Uri( "http://www.yahoo.com" ) ).Repeat.AtLeastOnce();
 context.Expect( c => c.Request ).Return( request ).Repeat.Any();

 fakeController.HttpContext = context;
tvanfosson
+1 I started to type a similar answer using Moq but you beat me to it
AdamRalph
hey tvanfosson, tried messing around with this code snippet, but I'm getting and error for context.Expect()Argument '1': cannot convert from 'System.Web.HttpRequestBase' to 'System.Web.HttpRequest'
kingrichard2005
A: 

You are going to need to create an entire mock HttpContext in order to accomplish this unfortunately. Rather than hardcoding this, I would highly suggest using mocks, as this will let you avoid setting up pieces of the object that you don't actually need.

I would suggest checking out Scott Hanselmann's MvcMockHelpers post to get some idea of what is involved (it includes code for both Rhino and Moq).

womp