单元测试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"]); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- Asp.Net MVC 3 JSON模型绑定无法正常工作
- asp.net-mvc – 带有jquery-file-upload的asp.ne
- Orchard Core一分钟搭建ASP.NET Core CMS
- asp.net-mvc – 为什么MVC提供的Default Account
- 事件(Event),绝大多数内存泄漏(Memory Leak)的
- 为什么Asp.Net MVC 5在_Layout.cshtml的底部放置
- asp.net-mvc – MVC DropDownListFor在视图中基本
- asp.net – 多个选择列表框而不按CTRL
- asp.net-mvc-3 – Elmah和ASP.NET MVC 3
- asp.net-mvc – 在AppHarbor上获取文件内容
热点阅读