Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Keys and Values to RouteData when using MVCContrib to unit test MVC 3 controllers and Views

Okay so I am using MVCContrib TestHelper to unit test my controllers, which works great.

Like so many people though, by unit test I really mean integration test here and I want to at least make sure my views render without error given the model provided...otherwise I can miss a whole class of bugs basically related to the model even though I am testing the controller (like the view not rendering if a model property is null).

Anyway I started trying to figure out how to do this (aka googling how to do it). It seemed like the easiest way was to construct an HTMLHelper and have it just render the views (partial in this case).

Unfortunately when I try to use my mocked HTMLHelper it complains that is doesn't have the controller name available in the route data.

Sure enough, I look and the controllers RouteData is not populated. Unfortunately the RouteData.Values RouteValueDictionary is read only, so I can't just supply the necessary values.

I'm not married to the HTMLHelper idea to solve the problem of actually rendering the view as part of the test, so feel free to suggest alternatives there, but please don't bother suggesting I test my Views using Selenium, Watin or other UI testing tools...I want the control to be able to do things like manipulate and restore state and data info for some of the tests, which I cannot do with UI based testing.

Here is the code I am currently using to try to render the partial:

    public class FakeView : IView
{
    #region IView Members
    public void Render(ViewContext viewContext, System.IO.TextWriter writer)
    {
        throw new NotImplementedException();
    }
    #endregion
}

public class WebTestUtilities
{
    public static void prepareCache()
    {
        SeedDataManager seed = new SeedDataManager();
        seed.CheckSeedDataStatus();
    }

    public static string RenderRazorViewToString(string viewName, object model, Controller controller)
    {
        var sb = new StringBuilder();
        var memWriter = new StringWriter(sb);
        var html = new HtmlHelper(new ViewContext(controller.ControllerContext,
            new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), memWriter),
            new ViewPage());
        //This fails because it can't extract route information like the controller name)
        html.RenderPartial(viewName, model);
        return sb.ToString();
    }


    public void setupTestEnvironment(Controller controller)
    {
        RouteTable.Routes.Clear();
        RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteTable.Routes.MapRoute(
            "Default", 
            "{controller}/{action}/{id}", 
            new { controller = "Main", action = "DefaultView", id = UrlParameter.Optional } 
        );




        ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();
        ModelBinders.Binders[typeof(DateTime?)] = new DateTimeModelBinder();
        ModelMetadataProviders.Current = new DateTimeMetadataProvider();



    }
}

And here is my test method:

        [TestMethod]
    public void GetUserTableView()
    {
        ViewResult result = controller.UserTable() as ViewResult;

        //I can populate the route and handler on the controller...
        RouteData routes = RouteTable.Routes.GetRouteData(controller.HttpContext);
        controller.RouteData.Route = routes.Route;
        controller.RouteData.RouteHandler = routes.RouteHandler;
        RouteValueDictionary routeKeys = new RouteValueDictionary();
        routeKeys.Add("controller", "UserManagement");
        routeKeys.Add("action", "UserTable");
        //But the RouteData.Values collection is read only :(
        controller.RouteData = new RouteData(){Values = routeKeys};
        string renderedView = WebTestUtilities.RenderRazorViewToString(result.ViewName, result.Model, controller);
    }

BTW, the specific error I get is : The RouteData must contain an item named 'controller' with a non-empty string value.

like image 422
Amasuriel Avatar asked Mar 22 '12 22:03

Amasuriel


2 Answers

You may have already worked this out, but I just had a similar problem and solved setting the RouteData by resetting the ControllerContext on the controller like so:

RouteData routeData = new RouteData();
routeData.Values.Add("someRouteDataProperty", "someValue");
ControllerContext controllerContext = new ControllerContext { RouteData = routeData };
controller.ControllerContext = controllerContext;

and then in the controller RouteData.Values.ContainsKey("someRouteDataProperty") works as you've set up in the test.

This works because there's a parameterless constructor of the ControllerContext that's deliberately there to allow mocking etc.

like image 196
stevie_c Avatar answered Nov 01 '22 20:11

stevie_c


You can override Controllers ControllerContext.RouteData - its virtual and RouteData property is just using it to read from.

From the reflected code of asp.net mvc RouteData property:

public RouteData RouteData 
{ 
    get 
    {
        return ControllerContext == null ? null : ControllerContext.RouteData; 
    }
}
like image 32
Sly Avatar answered Nov 01 '22 20:11

Sly