单元测试UrlHelper扩展

时间:2019-04-30 13:36:46

标签: c# asp.net-core mstest

我在ASP.NET Core项目中为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 });
    }

1 个答案:

答案 0 :(得分:3)

测试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,以详细了解其工作原理。