Asp.NET 使用 Telerik Just Mock Lite 进行 MVC 区域注册路由单元测试

Asp.NET MVC Arearegistration Route Unit Test With Telerik Just Mock Lite

我正在尝试 Asp.NET MVC 管理区域路由联合测试与 telerik 只是模拟 lite.But 我无法测试。

这是我的尝试代码:

        [TestMethod]
    public void AdminRouteUrlIsRoutedToHomeAndIndex()
    {
        //spts.saglik.gov.tr/admin
        //create route collection
        var routes = new RouteCollection();

        var areaRegistration = new AdminAreaRegistration();
        Assert.AreEqual("Admin",areaRegistration.AreaName);

        // Get an AreaRegistrationContext for my class. Give it an empty RouteCollection
        var areaRegistrationContext = new AreaRegistrationContext(areaRegistration.AreaName, routes);
        areaRegistration.RegisterArea(areaRegistrationContext);

        // Mock up an HttpContext object with my test path (using Moq)
        var context = Mock.Create<HttpContext>();
        context.Arrange(c=>c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/Admin");

        // Get the RouteData based on the HttpContext
        var routeData = routes.GetRouteData(context.Request.RequestContext.HttpContext);

        //assert has route
        Assert.IsNotNull(routeData,"route config");

    }

var context = Mock.Create<HttpContext>(); just mock 告诉这个错误

Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'System.Web.HttpContext'. JustMock Lite can only mock interface members, virtual/abstract members in non-sealed classes, delegates and all members on classes derived from MarshalByRefObject on instances created with Mock.Create or Mock.CreateLike. For any other scenario you need to use the full version of JustMock.

那么如何使用 telerik just mock lite 进行区域注册路由单元测试?我该如何解决这个问题?

非常感谢。

HttpContext 是你不能嘲笑的东西。它包含的数据特定于特定请求。因此,为了 运行 使用 HttpContext 进行测试,您实际上 运行 您的应用程序处于可以向其发出请求的环境中。

相反,您需要使用第三方工具,例如 MvcRouteTest (https://github.com/AnthonySteele/MvcRouteTester)。它易于使用,最重要的是,您可以 运行 测试而无需 运行 安装您的应用程序。

[TestMethod]
public void AdminRouteUrlIsRoutedToHomeAndIndex()
{
    var routes = new RouteCollection();

    var areaRegistration = new AdminAreaRegistration();
    Assert.AreEqual("Admin", areaRegistration.AreaName);

    var areaRegistrationContext = new AreaRegistrationContext(areaRegistration.AreaName, routes);
    areaRegistration.RegisterArea(areaRegistrationContext);

    routes.ShouldMap("/admin").To<HomeController>(r => r.Index());
}

这会同时测试区域注册和/admin URL 的路由(有些人认为它应该分成两个测试)。它假定您的 AdminAreaRegistrationRegisterArea() 方法构建默认路由,默认控制器设置为 Home:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { controller="home", action = "Index", id = UrlParameter.Optional }
    );
}