单元测试 UrlHelper 扩展

Unit testing UrlHelper extensions

我在 ASP.NET 核心项目中为 UrlHelper 编写了几个扩展方法。现在我想为他们编写单元测试。但是,我的许多扩展方法都利用了 UrlHelper 的方法(例如,Action),因此我需要将有效的 UrlHelper 传递给 this 参数(或有效的 UrlHelper 以调用方法)。

如何实例化一个可用的 UrlHelper?我试过这个:

        Mock<HttpContext> mockHTTPContext = new Mock<HttpContext>();
        Microsoft.AspNetCore.Mvc.ActionContext actionContext = new Microsoft.AspNetCore.Mvc.ActionContext(
            new DefaultHttpContext(), 
            new RouteData(), 
            new ActionDescriptor());
        UrlHelper urlHelper = new UrlHelper(actionContext);

        Guid theGUID = Guid.NewGuid();

        Assert.AreEqual("/Admin/Users/Edit/" + theGUID.ToString(), UrlHelperExtensions.UserEditPage(urlHelper, theGUID));

此调用堆栈崩溃(Test method Test.Commons.Admin.UrlHelperTests.URLGeneration threw exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index):

   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values)
   at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext)
   at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Action(IUrlHelper helper, String action, String controller, Object values)
   at <MY PROEJCT>.UrlHelperExtensions.UserEditPage(IUrlHelper helper, Guid i_userGUID) 
   at <MY TEST>.URLGeneration()

扩展方法的示例如下:

    public static string UserEditPage(this IUrlHelper helper, Guid i_userGUID)
    {
        return helper.Action(
            nameof(UsersController.EditUser), 
            "Users", 
            new { id = i_userGUID });
    }

测试 UrlHelper 扩展的最佳选择是模拟 IUrlHelper,例如使用最小起订量:

// arrange
UrlActionContext actual = null;
var userId = new Guid("52368a14-23fa-4c7f-a9e9-69b44fafcade");

// prepare action context as necessary
var actionContext = new ActionContext
{
    ActionDescriptor = new ActionDescriptor(),
    RouteData = new RouteData(),
};

// create url helper mock
var urlHelper = new Mock<IUrlHelper>();
urlHelper.SetupGet(h => h.ActionContext).Returns(actionContext);
urlHelper.Setup(h => h.Action(It.IsAny<UrlActionContext>()))
    .Callback((UrlActionContext context) => actual = context);

// act
var result = urlHelper.Object.UserEditPage(userId);

// assert
urlHelper.Verify();
Assert.Equal("EditUser", actual.Action);
Assert.Equal("Users", actual.Controller);
Assert.Null(actual.RouteName);

var values = new RouteValueDictionary(actual.Values);
Assert.Equal(userId, values["id"]);

查看 ASP.NET Core 的 UrlHelperExtensionsTest,详细了解其工作原理。