I'm trying to write a test for an UrlHelper extensionmethod that is used like this:
Url.Action<TestController>(x => x.TestAction());
However, I can't seem set it up correctly so that I can create a new UrlHelper and then assert that the returned url was the expected one. This is what I've got but I'm open to anything that does not involve mocking as well. ;O)
[Test]
public void Should_return_Test_slash_TestAction()
{
// Arrange
RouteTable.Routes.Add("TestRoute", new Route("{controller}/{action}", new MvcRouteHandler()));
var mocks = new MockRepository();
var context = mocks.FakeHttpContext(); // the extension from hanselman
var helper = new UrlHelper(new RequestContext(context, new RouteData()), RouteTable.Routes);
// Act
var result = helper.Action<TestController>(x => x.TestAction());
// Assert
Assert.That(result, Is.EqualTo("Test/TestAction"));
}
I tried changing it to urlHelper.Action("Test", "TestAction") but it will fail anyway so I know it is not my extensionmethod that is not working. NUnit returns:
NUnit.Framework.AssertionException: Expected string length 15 but was 0. Strings differ at index 0.
Expected: "Test/TestAction"
But was: <string.Empty>
I have verified that the route is registered and working and I am using Hanselmans extension for creating a fake HttpContext. Here's what my UrlHelper extentionmethod look like:
public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> actionExpression) where TController : Controller
{
var controllerName = typeof(TController).GetControllerName();
var actionName = actionExpression.GetActionName();
return urlHelper.Action(actionName, controllerName);
}
public static string GetControllerName(this Type controllerType)
{
return controllerType.Name.Replace("Controller", string.Empty);
}
public static string GetActionName(this LambdaExpression actionExpression)
{
return ((MethodCallExpression)actionExpression.Body).Method.Name;
}
Any ideas on what I am missing to get it working??? / Kristoffer