Solved

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

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

758 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now