Proper MVC Controller mocking

6 posts, 0 answers
  1. Mihai
    Mihai avatar
    4 posts
    Member since:
    Aug 2010

    Posted 04 Mar 2011 Link to this post


    Having played around with JustMock, I couldn't figure out how to test a controller action properly. I can't seem to figure out how to properly instantiate the controller (with request, session etc).

    Here's a controller with a simple action (which renders a custom login form):

    public class LoginController : Controller
            public ActionResult LogOn(string company)
                ViewData["showCompany"] = company == null;
                ViewData["company"] = company;
                return View();

    I'd like to write a test on this method, but have no idea how to correctly instantiate the controller object. Having created the following test attempt, it doesn't work. When debugging it the action is not fully executed and the actionResult is null:

                // arrange
                var outputString = new StringWriter();
                var context = new HttpContextWrapper(new HttpContext(new HttpRequest("/", "http://localhost/mft/Login/LogOn", ""), new HttpResponse(outputString)));
                var loginController = new LoginController();

                Mock.Arrange(() => loginController.HttpContext).Returns(context);
                Mock.Arrange(() => loginController.LogOn("mft")).MustBeCalled();

                // act
                var actionResult = loginController.LogOn("mft");

                // assert

    I realized the ViewData is null so I modified the test like so:
                loginController.ViewData = new ViewDataDictionary();

    However, this doesn't seem to be solving the problem. The actionResult keeps being null and I feel like I'm going the wrong way. There should be a simple way to instantiate a controller and call an action. Later on I will have to use a session cookie that I can get by calling something like:
    [AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string userName, string password, string company, string returnUrl){}

    I've been looking for examples all over but just couldn't find one that works.

  2. Ricky
    Ricky avatar
    467 posts

    Posted 07 Mar 2011 Link to this post

    Hi Mihai,

    Thanks for bringing up the question. To get things started, I created an MVC 2 project from default project template and added a test that shows how to assert ViewData items once controller action is invoked.

    Here the steps include:

    1. Create the controller instance with mocked HttpContextBase. You possibly don’t need to mock the controller class itself since you will be invoking the action manually or your test code will always be under an action.

    2. Invoke the action (LogOn) and assert the view result. Your action can have additional calls to external classes. In that case, mock them as well and setup using Mock.Arrange/ property setter, during controller instantiation.

    Finally, please find the attached project for more info. I have used JustMock free edition for the purpose and do feel free to write us back for further confusions.

    Kind Regards,
    the Telerik team

    Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
  3. DevCraft R3 2016 release webinar banner
  4. Daryl Shenner
    Daryl Shenner avatar
    46 posts
    Member since:
    Dec 2009

    Posted 26 Jun 2012 Link to this post


    Below is my telerik grid which works perfect

    <table border="0" cellpadding="0" cellspacing="0" width="100%">
            <tr align="center">
                <td align="center">
                                          .DataKeys(dataKeys =>
                                              dataKeys.Add(o => o.ContactID);
                                          .DataBinding(dataBinding =>
                                                          .Select("SelectContacts", "Opportunity"))
                                          .Columns(columns =>
                                              columns.Command(commands => commands.Custom("GetSelectedContactDetails").Text("Select").DataRouteValues(route => route.Add(o => o.ContactID).RouteKey("ContactID"))
                                                    .Ajax(true).Action("GetSelectedContactDetails", "Opportunity")).Width(90);

                                              columns.Bound(o => o.ContactID).Hidden(true);
                                              columns.Bound(o => o.FirstName).Width(150).Title("First Name");
                                              columns.Bound(o => o.Address1).Width(150).Title("Address1");
                                              columns.Bound(o => o.Email).Width(150).Title("Email");
                                              columns.Bound(o => o.MobilePhone).Width(150).Title("Mobile Phone");
                                              columns.Bound(o => o.WorkPhone).Width(150).Title("Work Phone");
                                          .ClientEvents(events => events.OnLoad("OnContactLoad").OnComplete("OnComplete"))
                                      .Pageable(paging => paging.PageSize(10)
                                      .Scrollable(scrolling => scrolling.Height(290))
                                      .Sortable().Reorderable(reorder => reorder.Columns(true))
                                      .Resizable(resizing => resizing.Columns(true))
                                      .HtmlAttributes(new { style = " align=center; font-family:arial; font-size: .7em;width:370px;" }))

    I want to unit test the view of my application. Below is the code that I use to unit test my view

                var view = new Opportunityview();
                view.ViewBag.Title = "Testing";    
                HtmlDocument doc = view.RenderAsHtml();
                HtmlNode node = doc.DocumentNode.Element("h2");

    When I call RenderAsHtml, I get the "null reference" exception. When I view the details, the source of the error was "Telerik.web.mvc". I added the dll to my test project. Even though, I couldn't succeed.  When I comment the grid design code and run the test, there is no issue.

    I'd like to have some help from your side or any sample project or any links that test the View of an MVC razor application which has telerik grid.
  5. Ricky
    Ricky avatar
    467 posts

    Posted 29 Jun 2012 Link to this post

    Hi Daryl,

    Thanks again for contacting us. Here the best way to mock the RenderHtml  method from OpportunityView is the following way:

    Mock.Arrang(() => view.RenderHtml()).DoNothing();

    Here I am partially mocking the RenderHtml just to skip the original method invocation.

    Kind Regards
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

  6. Daryl Shenner
    Daryl Shenner avatar
    46 posts
    Member since:
    Dec 2009

    Posted 03 Jul 2012 Link to this post

    Hi, Thanks for your response.

    Can I have a sample test method to test the view? I get error while compile the line that you sent. 

    Can I have sample project
  7. Ricky
    Ricky avatar
    467 posts

    Posted 06 Jul 2012 Link to this post

    Hi Mihai,

    Sorry for the late reply. However, there was an issue in my previous snippet. It should look like:


    This line should be called once after the mock OpportunityView is created. The "view" here is the mock instance of OpportunityView.

    Optionally, it will be better if you can send me the sample project or test you are working with. In this way , i will be able to take a closer look into it.

    Kind Regards
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Back to Top
DevCraft R3 2016 release webinar banner