Create a reference URL in ASP.Net MVC for unit testing

I am currently testing my application and trying to figure out how to create my own fake URL. I tried hard-coded it, but I get an error that it is read-only. Here is what I have tried so far:

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

as well as

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

I searched the web for some ideas on how to create a fake / mock url for my fake controller, but no luck. Any suggestions are welcome.

Note. I am using Visual Studios built-in testing tools.

UPDATE:

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

+5
source share
4 answers

I recommend switching to the Mock Framework, such as NMock or Rhino Mock, which allows you to create them and returns a specific value for a given call, for example, the get method in this property.

+1
source

mock- HttpContext, , Uri. 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;
+7

tvanfosson , . ( OP MOQ, )

    // 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

+2

HttpContext , . mocks, , .

Scott Hanselmann MvcMockHelpers, , ( Rhino Moq).

+1

All Articles