Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mock URL referrer in ASP.Net MVC for Unit Testing

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.

like image 226
kingrichard2005 Avatar asked Feb 10 '10 17:02

kingrichard2005


3 Answers

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;
like image 195
tvanfosson Avatar answered Nov 05 '22 20:11

tvanfosson


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

like image 22
lko Avatar answered Nov 05 '22 19:11

lko


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.

like image 1
jpabluz Avatar answered Nov 05 '22 19:11

jpabluz