Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Mock controller.Url.Action

Tags:

Urls for menus in my ASP.NET MVC apps are generated from controller/actions. So, they call

controller.Url.Action(action, controller) 

Now, how do I make this work in unit tests? I use MVCContrib successfully with

var controller = new TestControllerBuilder().CreateController<OrdersController>(); 

but whatever I try to do with it I get controller.Url.Action(action, controller) failing with NullReferenceException because Url == null.

Update: it's not about how to intercept HttpContext. I did this in several ways, using MVCContrib, Scott Hanselman's example of faking, and also the one from http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx. This doesn't help me because I need to know WHAT values to fake... is it ApplicationPath? How do I set it up? Does it need to match the called controller/action? That is, how do Url.Action works and how do I satisfy it?

Also, I know I can do IUrlActionAbstraction and go with it... but I'm not sure I want to do this. After all, I have MVCContrib/Mock full power and why do I need another abstraction.

like image 637
queen3 Avatar asked Sep 02 '09 13:09

queen3


1 Answers

A cleaner way to do this is just use Moq(or any other framework you like) to Mock UrlHelper itself

var controller = new OrdersController(); var UrlHelperMock = new Mock<UrlHelper>();  controller.Url = UrlHelperMock.Object;  UrlHelperMock.Setup(x => x.Action("Action", "Controller", new {parem = "test"})).Returns("testUrl");  var url = controller.Url.Action("Action", "Controller", new {parem = "test"}); assert.areEqual("/Controller/Action/?parem=test",url); 

clean and simple.

like image 74
Bob The Janitor Avatar answered Oct 25 '22 14:10

Bob The Janitor