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.
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 ).Returns( new Uri( "http://www.yahoo.com" ) ).Repeat.AtLeastOnce();
context.Expect( c => c.Request ).Returns( request ).Repeat.Any();
fakeController.HttpContext = context;
tvanfosson's Answer is in the right direction but is a little outdated. (Granted OP couldn't use MOQ, added for future reference)
// Dependency Mocks initialization ....
....
MyController controller = new MyController(mock.Object, ...dependencies...);
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.UrlReferrer).Returns(new Uri("http://www.site.com"));
context.Setup(c => c.Request).Returns(request.Object);
// Setting the HttpContext
// 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);
//target.HttpContext = context.Object; // outdated
HttpContext from Controller context
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.
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