floormind
floormind

Reputation: 2028

UrlHelper mock is not working

I am trying to write get write a unit test that passes but the method my test calls, calls another method which generates a URL using the UrlHelper class. The result of calling urlHelper.Action keeps returning null.

I have tried mocking (using Moq) all the components i assume this controller will need to be able to get this working, but I am still getting null.

Unit Test Class

[TestFixtureSetUp]
public void Configure_Defaults()
{

    var mockHttpContextBase = new Mock<HttpContextBase>();

    var mockRequest = new Mock<HttpRequestBase>();

    var mockControllerContext = new Mock<ControllerContext>();

    var mockWebRoutingRequestContrext = new Mock<RequestContext>();

    mockRequest
        .Setup(request => request.Url)
        .Returns(new Uri("http://dev.fleepos.local/Register"));

    mockHttpContextBase
        .Setup(httpContext => httpContext.Request)
        .Returns(mockRequest.Object);

    mockWebRoutingRequestContrext
        .Setup(request => request.HttpContext)
        .Returns(mockHttpContextBase.Object);

    mockWebRoutingRequestContrext
        .Setup(request => request.RouteData)
        .Returns(new RouteData());

    var urlHelper = new UrlHelper(mockWebRoutingRequestContrext.Object);

    mockControllerContext
        .Setup(controllerContext => controllerContext.HttpContext)
        .Returns(mockHttpContextBase.Object);


    _registerController = new RegisterController() {ControllerContext = mockControllerContext.Object, Url = urlHelper};

}

[Test]
public void Display_Validate_Account_Page_On_Successful_Registration()
{
    //act
    var result = (RedirectToRouteResult)_registerController.Register(_userRegisterationViewModel);

    //assert
    Assert.That(result.RouteValues["action"], Is.EqualTo("ValidateAccount"));
}

Controller method called by controller action

private string GenerateActionLink(string actionName, string token, string username)
{
    string validationLink = null;
    if (Request.Url != null)
    {
        var urlHelper = new UrlHelper(ControllerContext.RequestContext);
        validationLink = urlHelper.Action(actionName, "Register",
            new { Token = token, Username = username },
            Request.Url.Scheme);
    }

    return validationLink;
}

Upvotes: 4

Views: 1542

Answers (1)

Nkosi
Nkosi

Reputation: 247068

The controller already has a UrlHelper Url property that can be mocked to do what you want. By creating a new UrlHelper in the controller method called by controller action, the opportunity to substitute a mock/fake is lost.

First update the controller method called by controller action to make it test friendly

private string GenerateActionLink(string actionName, string token, string username) {
    string validationLink = null;
    if (Request.Url != null) {
        validationLink = Url.Action(actionName, "Register",
            new { Token = token, Username = username },
            Request.Url.Scheme);
    }

    return validationLink;
}

Now there is more control of the controller's UrlHelper. The UrlHelper can be mocked as well and passed to the controller context

Here is a minimal complete example of what was explained above.

[TestClass]
public class UrlHelperTest {
    [TestMethod]
    public void MockUrlHelper() {
        //Arrange
        var requestUrl = new Uri("http://myrequesturl");
        var request = Mock.Of<HttpRequestBase>();
        var requestMock = Mock.Get(request);
        requestMock.Setup(m => m.Url).Returns(requestUrl);

        var httpcontext = Mock.Of<HttpContextBase>();
        var httpcontextSetup = Mock.Get(httpcontext);
        httpcontextSetup.Setup(m => m.Request).Returns(request);


        var actionName = "MyTargetActionName";
        var expectedUrl = "http://myfakeactionurl.com";
        var mockUrlHelper = new Mock<UrlHelper>();
        mockUrlHelper
            .Setup(m => m.Action(actionName, "Register", It.IsAny<object>(), It.IsAny<string>()))
            .Returns(expectedUrl)
            .Verifiable();

        var sut = new MyController();
        sut.Url = mockUrlHelper.Object;
        sut.ControllerContext = new ControllerContext {
            Controller = sut,
            HttpContext = httpcontext,
        };

        //Act
        var result = sut.MyAction();

        //Assert
        mockUrlHelper.Verify();
    }

    public class MyController : Controller {
        [HttpPost]
        public ActionResult MyAction() {
            var link = GenerateActionLink("MyTargetActionName", string.Empty, string.Empty);

            return View((object)link);
        }

        private string GenerateActionLink(string actionName, string token, string username) {
            string validationLink = null;
            if (Request.Url != null) {
                var encodedToken = EncodedUrlParameter(token);
                var url = Url.Action(actionName, "Register", new { Token = encodedToken, Username = username }, Request.Url.Scheme);
                validationLink = url;
            }

            return validationLink;
        }

        private string EncodedUrlParameter(string token) {
            return "Fake encoding";
        }

    }
}

Upvotes: 2

Related Questions