سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top