Solved

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

Posted on 2014-09-05
2
510 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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

831 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