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. :)

tereško
  • 56,151
  • 24
  • 92
  • 147
core
  • 30,054
  • 41
  • 131
  • 189
  • This should be really helpfull http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq – Jordy Langen Aug 15 '13 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). – core Aug 15 '13 at 21:03
  • I looked around, and found some interesting things. Take a look at this gist: https://gist.github.com/johnnyreilly/4959924 – Jordy Langen Aug 16 '13 at 07:19
  • And this SO: http://stackoverflow.com/questions/674458/asp-net-mvc-unit-testing-controllers-that-use-urlhelper/675269#675269 – Jordy Langen Aug 16 '13 at 07:19
  • Jordan, please submit your comments as answer and I will mark as accepted. Thank you for your help! – core Aug 16 '13 at 15:08

2 Answers2

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.

Community
  • 1
  • 1
Jordy Langen
  • 3,511
  • 4
  • 21
  • 32
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/

GDB
  • 2,365
  • 2
  • 23
  • 31