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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With