Sim*_*one 0 c# mstest asp.net-core
我在 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));
Run Code Online (Sandbox Code Playgroud)
它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()
Run Code Online (Sandbox Code Playgroud)
扩展方法的示例如下:
public static string UserEditPage(this IUrlHelper helper, Guid i_userGUID)
{
return helper.Action(
nameof(UsersController.EditUser),
"Users",
new { id = i_userGUID });
}
Run Code Online (Sandbox Code Playgroud)
测试 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"]);
Run Code Online (Sandbox Code Playgroud)
查看ASP.NET Core 的UrlHelperExtensionsTest,了解其详细工作原理。
| 归档时间: |
|
| 查看次数: |
1613 次 |
| 最近记录: |