1

I'm trying to learn unit testing, and have this super simple class, with unit test:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new HomeViewModel
        {
            LogoUrl = this.Url.Content("~/Images/product.png")
       });
    }
}

[TestMethod]
public void Index()
{
    Assert.IsNotNull(new HomeController().Index() as ViewResult);
}

I'm getting null reference exceptions. It's related to using this.Url() without an HttpContext in the unit test, I believe.

How can I get the unit test to pass while still using my this.Url()? I'm fine with using Moq. :)

5
  • This should be really helpfull stackoverflow.com/questions/1452418/… Commented Aug 15, 2013 at 15:53
  • I actually did that. I still get a null reference. Without using Reflector (don't have a license), I can't see how this.Url works (i.e. can't see exactly what I need to mock). Commented Aug 15, 2013 at 21:03
  • I looked around, and found some interesting things. Take a look at this gist: gist.github.com/johnnyreilly/4959924 Commented Aug 16, 2013 at 7:19
  • And this SO: stackoverflow.com/questions/674458/… Commented Aug 16, 2013 at 7:19
  • Jordan, please submit your comments as answer and I will mark as accepted. Thank you for your help! Commented Aug 16, 2013 at 15:08

2 Answers 2

2

The answer can be found here as an example (gist): https://gist.github.com/johnnyreilly/4959924

Here is a relating Stack Overflow question: ASP.NET MVC: Unit testing controllers that use UrlHelper

Both should help you get on the right tracks.

It comes down to mocking the HttpRequestBase and the HttpResponseBase so you can mock the actual HttpContextBase, which is being used by the UrlHelper class.

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

Comments

0

Realize this is an old question but for others who might stop by, check out Unit Testing Simple ASP.NET MVC Controllers by the always helpful crew at LosTechies: http://lostechies.com/chrismissal/2010/02/05/unit-testing-simple-asp-net-mvc-controllers/

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.