2

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.

3
  • stackoverflow.com/questions/674458/… Commented Jan 16, 2012 at 20:54
  • 2
    You didn't shown neither your unit test neither what the Url.Home() method is and how is it implemented as obviously such method doesn't exist in the UrlHelper class. And you expect an answer? Commented Jan 16, 2012 at 20:55
  • Updated the question with more details. Commented Jan 16, 2012 at 22:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.