Solved

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

Posted on 2014-09-05
2
549 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Please explain purpose of GZIP 4 61
SSRS Deployment problem 5 97
C# Linq Select From List 3 48
Set custom font WPF 2 22
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project

730 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