Reputation: 33071
I recently changed most of my Controllers to use Url helper extensions instead of using RedirectToAction, etc:
public ActionResult Create(CreateModel model)
{
// ...
return Redirect(Url.Home());
}
This has currently made my unit tests break with NullReference exceptions. What is the proper way to mock/stub a UrlHelper so I can get my unit tests working again?
Edit:
My Url extension looks like this:
public static class UrlHelperExtensions
{
public static string Home(this UrlHelper helper)
{
return helper.RouteUrl("Default");
}
}
My unit test is just testing to make sure that they are redirected to the correct page:
// Arrange
var controller = new HomeController();
// Act
var result = controller.Create(...);
// Assert
// recalling the exact details of this from memory, but this is what i'm trying to do:
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
Assert.AreEqual(((RedirectToRouteResult)result).Controller, "Home");
Assert.AreEqual(((RedirectToRouteResult)result).Action, "Index");
What is happening now is when I call Url.Home() but I get a nullreference error. I tried setting the Url property with a new UrlHelper but it still gets a null reference exception.
Upvotes: 2
Views: 541
Reputation: 11673
I think your better off abstracting out your extensions for example:
public interface IUrls
{
string Home();
}
public class Urls : IUrls
{
public string Home()
{
//impl
}
}
Then constructor inject that wherever needed, then you can easily Stub 'IUrls' for your tests.
Upvotes: 1