This is a migrated thread and some comments may be shown as answers.

Proper MVC Controller mocking

5 Answers 320 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Mihai
Top achievements
Rank 1
Mihai asked on 04 Mar 2011, 01:53 PM
Hi,

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
            Mock.Assert(loginController);


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.

Thanks,
Mihai

5 Answers, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 07 Mar 2011, 12:52 PM
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,
Ricky
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!
0
Daryl Shenner
Top achievements
Rank 1
answered on 26 Jun 2012, 12:07 PM
Hi,

Below is my telerik grid which works perfect

<table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr align="center">
            <td align="center">
                @{  
                    @(Html.Telerik().Grid<HomeFrontCRM.Web.UI.Models.ContactDetailsModels>()
                                          .Name("AssignContactGrid")
                                      .DataKeys(dataKeys =>
                                      {
                                          dataKeys.Add(o => o.ContactID);
                                      })
                                      .DataBinding(dataBinding =>
                                          dataBinding.Ajax()
                                                      .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)
                                  .Style(GridPagerStyles.NextPreviousAndDropDown))
                                  .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;" }))
                }
            </td>
        </tr>
    </table>

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.
0
Ricky
Telerik team
answered on 29 Jun 2012, 12:52 PM
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
Ricky
the Telerik team

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

0
Daryl Shenner
Top achievements
Rank 1
answered on 03 Jul 2012, 05:21 AM
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
0
Ricky
Telerik team
answered on 06 Jul 2012, 02:50 PM
Hi Mihai,

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

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

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
Ricky
the Telerik team

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

Tags
General Discussions
Asked by
Mihai
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Daryl Shenner
Top achievements
Rank 1
Share this question
or