0

I am trying to set the controller.Url property, but this test fails.

I wrote this test because I could not test a controller action due to controller.Url being null.

    [TestMethod]
public void AccountController_Url_ShouldNotBeNull()
{
    var target = new AccountController();
    var url = new UrlHelper(
        this.RequestContext(this.GetFakeHttpContextBase), 
        new RouteCollection());
    target.Url = url;

    target.Url.Should().NotBeNull();
}

I am using FakeItEasy to mock my HttpContextBase, etc. Any ideas?

Rick Rat
  • 1,732
  • 1
  • 16
  • 32
  • If you are setting the Url property on your AccountController and an immediate test for non-null on that property is failing, then I suggest that the problem is nothing to do with testing and/or FakeItEasy. It seems like there's just something wrong with your AccountController. It may help if you try and isolate the problem as much as possible to prove/disprove this. – Adam Ralph May 29 '13 at 18:43

1 Answers1

3

You should consider stubbing out the urlHelper itself, something like (I'm using NMock - but I believe the semantics should be similar for your mocking framework):

        var target = new AccountController();
        var urlHelper = MockRepository.GenerateMock<UrlHelper>();

        target.Url = urlHelper;
        //Now you could stub the various functions of urlHelper, like:
        //urlHelper.Stub(u => u.IsLocalUrl("blahUrl")).Return(true);

There are a few other issues as well. UrlHelper doesn't have virtual methods, and hence stubbing the methods would be difficult. In such a case, you can have a wrapper over UrlHelper - and inject it into the controller. Use the wrapper and delegate the calls to the actual urlHelper instance.

Thus, your controller would not interact directly with the urlHelper. Instead, it would talk to the wrapper. By having an interface for the wrapper, it'll be very easy to test the controller.

aquaraga
  • 4,138
  • 23
  • 29