使用Telerik Just Mock Lite的Asp.NET MVC Arearegistration路由单元测试

时间:2016-05-09 13:45:11

标签: c# asp.net-mvc unit-testing telerik justmock

我正在尝试将Asp.NET MVC Admin区域路由联合测试与telerik只是模拟lite。但我不能测试。

这是我的尝试代码:

CodeBehind="

[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>();

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

非常感谢。

1 个答案:

答案 0 :(得分:0)

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的路由(有些人认为它应该分为两个测试)。它假定您的AdminAreaRegistration RegisterArea()方法构建默认路由,默认控制器设置为Home:

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