Solved

How to unit test a controller that makes a call to Url.GetUrl

Posted on 2014-09-05
2
520 Views
Last Modified: 2014-09-08
I have the following action in my controller that I want to unit test:
        // Returns the ReferralType info along with the keys needed to find duplicate referrals for the selected Referral Type
        public JsonResult getURL(string actionName, string controllerName, string routeVals = null)
        {
            string url = "";

            if (routeVals == null || routeVals == "")
            {
                url = Url.RouteUrl(actionName, controllerName);
                
            }
            else
            {
                url = Url.Action(actionName, controllerName, new { id = routeVals });
            }

            return Json(url, JsonRequestBehavior.AllowGet);
        }

  

Open in new window


I created the following Unit Test:
        [TestMethod]
        public void getURL_Returns_URL_With_No_Parameters_When_RouteValues_Is_Null()
        {
            // Arrange
            var routes = new RouteCollection();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
            request.SetupGet(x => x.ApplicationPath).Returns("/");
            request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
            request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

            var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
            response.Setup(x => x.ApplyAppPathModifier("/post1")).Returns("http://localhost/post1");

            var context = new Mock<HttpContextBase>(MockBehavior.Strict);
            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Response).Returns(response.Object);

            InMemoryReferralsModelContainterRepository repository = imr.PopulateInMemoryRepository();

            var mockRequestProcessLogic = new Mock<RequestProcessLogic>(repository, new EmployeeProfileRecord(epimr));

            var controller = new RequestProcessController(repository, context.Object, mockRequestProcessLogic.Object);
            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
            controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

            // Act
            var result = controller.getURL("Index", "Home");

            // Assert
            Assert.AreEqual("/Home/Index", result.Data);
        }

Open in new window


The test fails because the getUrl action throws the following error:

A route named "Index" could not be found in the route collection.
Parameter name: name

The RequestProcessController does not have an Index method but the HomeController does.  Can someone point out what I am doing wrong in my Unit Test that is causing the error?

Any help is greatly appreciated!
0
Comment
Question by:dyarosh
2 Comments
 
LVL 21

Accepted Solution

by:
MogalManic earned 500 total points
ID: 40310448
I think this should help you:  http://icanmakethiswork.blogspot.com/2013/02/unit-testing-mvc-controllers-mocking.html

The only other choice would be to create an "adapter pattern" interface for the URLHelper class.  The default implementation would map to the System.Web.Mvc.UrlHelper class.  Then in the unit test the default could be replaced with a mock implementation of the interface.
0
 

Author Closing Comment

by:dyarosh
ID: 40310911
Thank you.  I was able to use the solution with some minor modifications.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Google Directions API to Map URL -C#? 3 37
.NET 2008 VB and C# 6 39
Save ms data to server side. 19 55
Why use this lambda? 12 31
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question