views:

645

answers:

2

Hi,

I have a paging controller with a method which calls

RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, valueDictionary)

I am trying to test this method using Rhino mocks and I'm unsure how to mock GetVirtualPath to return a route other than null. I am mocking the RequestContext but I am unsure which methods/properties need to be stubbed.

By stubbing the mockRequestContext appropriately should GetVirtualPath return a non null path, and if so what needs to be stubbed for this to work?

Any advice much appreciated.

+1  A: 

Not sure if I understand you question, but it looks like something like this:

IRouteTable routeTableMock = RhinoMocks.CreateMock<IRouteTable>();

// assuming that IRouteTable.Routes is of type IRoutes.
IRoutes routes = RhinoMocks.CreateMock<IRoutes>();

// return the routes with the mock
routeTableMock.Stub(x => x.Routes).Return(routes);

// setup the mock for GetVirtualPath
routes.Stub(
  x => x.GetVirtualPath(
    Arg<RequestContext>.Is.Anything, 
    Arg<IDictionary>.Is.Anything)
  .Return(/* whatever */);

if this is not what you are looking for, you have to tell more about your classes and what yo want to test.

Stefan Steinegger
The class has a viewContext passed during construction which is then used in a call to RouteTable.Routes.GetVirtualPath. This is called on the Sytem.Web.Routing.RoutingTable.RouteCollection class. Is there a way to stub the ViewContext so the call on Sytem.Web.Routing.RoutingTable.RouteCollection.GetVirtualPath will return a path?
TonE
Oh, this is something completely different, sorry. When you mock the ViewContext, you need to know what calls are made by GetVirtualPath. If ViewContext is a rather complex thing, you should consider to mock the whole stuff away.
Stefan Steinegger
Yeah, I guess that was my question - what calls are made by GetVirtualPath to enable me to mock the ViewContext in a way GetVirtualPath will return a value.Thanks for your input though - I guess I could put the GetVirtualPath behind an interface to remove the dependency for testing? Seems overkill for this simple case though...
TonE
if it is really that simple, you don't have to test it ;-)
Stefan Steinegger
+1  A: 

If you don't need the complete virtual path, but just the URL it generates, you can instead use:

new UrlHelper(ControllerContext.RequestContext).RouteUrl(routeValueDictionary)

... and mock out the ControllerContext:

var mockHttpContext = new Mock<HttpContextBase>();

var controllerContext
    = new ControllerContext(
        mockHttpContext.Object,
        new RouteData(), 
        new Mock<ControllerBase>().Object);

var myController = new MyController { ControllerContext = controllerContext };

I was having this exact problem but this appears to have solved it.

James Kolpack