单元测试ASP.NET MVC 2路线与AreaRegistration.RegisterAllAreas()

前端之家收集整理的这篇文章主要介绍了单元测试ASP.NET MVC 2路线与AreaRegistration.RegisterAllAreas()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在ASP.NET MVC中单元测试我的路线2.我正在使用MSTest,我也在使用区域。
[TestClass]
public class RouteRegistrarTests
{
    [ClassInitialize]
    public static void ClassInitialize(TestContext testContext)
    {
        RouteTable.Routes.Clear();

        RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        RouteTable.Routes.IgnoreRoute("{*favicon}",new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        AreaRegistration.RegisterAllAreas();

        routes.MapRoute(
            "default","{controller}/{action}/{id}",new { controller = "Home",action = "Index",id = UrlParameter.Optional }
        );
    }

    [TestMethod]
    public void RouteMaps_VerifyMappings_Match()
    {
        "~/".Route().ShouldMapTo<HomeController>(n => n.Index());
    }
}

当它执行AreaRegistration.RegisterAllAreas()但是,它抛出这个异常:

System.InvalidOperationException:System.InvalidOperationException:在应用程序的初始化初始化阶段期间无法调用方法

所以,我估计我不能从我的类初始化程序调用它。但是什么时候可以叫它?我显然没有一个Application_Start在我的测试。

解决方法

我通过创建一个我的AreaRegistration类的实例并调用RegisterArea方法解决这个问题。

例如,给定一个名为“目录”的区域与此路线:

public override void RegisterArea(AreaRegistrationContext context)
{
  context.MapRoute(
      "Catalog_default","Catalog/{controller}/{action}/{id}",new {controller = "List",id = "" }
  );
}

这是我的测试方法

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

  // Get my AreaRegistration class
  var areaRegistration = new CatalogAreaRegistration();
  Assert.AreEqual("Catalog",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 = new Mock<HttpContextBase>();
  context.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/Catalog");

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

  Assert.IsNotNull(routeData,"Should have found the route");
  Assert.AreEqual("Catalog",routeData.DataTokens["area"]);
  Assert.AreEqual("List",routeData.Values["controller"]);
  Assert.AreEqual("Index",routeData.Values["action"]);
  Assert.AreEqual("",routeData.Values["id"]);
}

猜你在找的asp.Net相关文章