How to create URL in ASP.Net MVC
This is probably a little old, but I am having some trouble so I figured I would start a post to see if I could help some people and possibly get some help myself. I have a Controller that is handling a shopping cart. The index method is pretty straight forward. Two parameters: the Cart it self and a returnURL as a string.
1 2 3 4 5 6 7 8 9 10 11 12 | public ViewResult Index(Cart cart, string returnUrl = null) { CartIndexViewModel model = new CartIndexViewModel(); model.Cart = cart; model.Cart.CartTotal = cart.ComputeTotalValue(); model.Cart.QtyTotal = cart.CalculateTotalQty(); model.ReturnUrl = String.IsNullOrWhiteSpace(returnUrl) ? Url.Action("Index", "Home") : returnUrl; return View(model); } |
The returnURL if it is empty should have a “default” URL that it can use. (This is where the trouble came in.) In trying to be a good developer I added a test method to test this particular piece of code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | [TestMethod] public void Cart_Index_Test() { Item i1 = new Item() { ID = 1, Title = "Test", Price = 12.95M }; Item i2 = new Item() { ID = 2, Title = "Test2", Price = 13.99M }; Cart cart = new Cart(); cart.AddItem(i1, 1); cart.AddItem(i2, 1); CartController target = new CartController(); ViewResult result = target.Index(cart); Assert.IsInstanceOfType(result, typeof(ViewResult)); } |
This is where the issue comes in. This test continually fails with a NullReferenceException. I originally thought it was that the returnUrl value was null. Which lead me to post a question on StackOverflow. (I will save that rant for another post.) Then as I was stepping through the debugger for the unit testing I discovered that the problem is not the returnURL being null, it is that the this.URL.Action object is actually null. (Which would not happen in a normal “live” or even a debugging environment. It is because I was running the test on that controller that caused the issue.
This brings me to the issue, how would one create a URL in an MVC controller as to avoid the NullReferenceException in the test, and still have the code work properly in production?