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;
}
The controller already has a
UrlHelper Urlproperty that can be mocked to do what you want. By creating anew UrlHelperin 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
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.