• Categories

  • Mocking HtmlHelpers in ASP.Net MVC

    NB: This post relates to version 1 of ASP.Net MVC

    I recently added a static extension method for generating a custom drop down list and wanted to test it using Rhino Mocks (version 3.5).
    One issue I kept banging my head against was how to create a Mock HtmlHelper in order to call the method correctly.
    A number of posts later, and various attempts at using some of the sample code and I finally came across this post detailing a bunch of MVC tests.

    After a minor amount of customising, I ended up with the following, which works like a charm for me to use in my tests.

            /// Creates a HTML helper for use in tests.
            private HtmlHelper CreateHtmlHelper()
                var userControl = new ViewUserControl();
                var container = new ViewPage();
                var context = MockRepository.GenerateMock<ViewContext>();
                userControl.ViewContext = context;
                return userControl.Html;

    Tags: ,

    Leave a Reply