加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 18:34:24 所属栏目:asp.Net 来源:网络整理
导读:我在ASP.NET MVC中单元测试我的路线2.我正在使用MSTest,我也在使用区域。 [TestClass]public class RouteRegistrarTests{ [ClassInitialize] public static void ClassInitialize(TestContext testContext) { RouteTable.Routes.Clear(); RouteTable.Routes
我在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"]);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读