单元测试UrlHelper扩展

问题描述 投票:0回答:1

我在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 });
    }
c# asp.net-core mstest
1个回答
3
投票

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

// 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,了解其工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.