views:

179

answers:

1

The moment I added a unit test to my ASP.NET MVC application to test some of the area routing, I got an HttpException coming out of the System.Web.Complication.CompilationLock type initializer with the following stack trace.

System.Web.HttpException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception.
  ----> System.TypeInitializationException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception.
  ----> System.NullReferenceException : Object reference not set to an instance of an object.
at System.Web.Compilation.BuildManager.ReportTopLevelCompilationException()
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
at System.Web.Compilation.BuildManager.GetReferencedAssemblies()
at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.GetReferencedAssemblies()
at System.Web.Mvc.TypeCacheUtil.FilterTypesInAssemblies(IBuildManager buildManager, Predicate`1 predicate)
at System.Web.Mvc.TypeCacheUtil.GetFilteredTypesFromAssemblies(String cacheName, Predicate`1 predicate, IBuildManager buildManager)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas()
at StpWeb.MvcApplication.RegisterRoutes(RouteCollection routes) in Global.asax.cs: line 16
at StpWeb.Tests.RoutesTest.TestFixtureSetUp() in RoutesTest.cs: line 11
--TypeInitializationException
at System.Web.Compilation.CompilationLock.GetLock(ref Boolean gotLock)
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
--NullReferenceException
at System.Web.Compilation.CompilationLock..cctor()
+2  A: 

For anyone else that followed the MVC Areas tutorials on MSDN, you will find an issue if you ever add unit tests to the web application you created.

It tells you to add AreaRegistration.RegisterAllAreas() to the RegisterRoutes method. Unfortunately, that is a static method that gets upset when called from unit tests.

Instead, register areas within Application_Start, right before the RegisterRoutes call you just modified. If you call RegisterRoutes first, UrlParameter.Optional appears to stop working in area routes (keeps working in non-area routes, though).

protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
}
patridge
I could have saved a few hours if I found [this person](http://aspnet.codeplex.com/WorkItem/View.aspx?WorkItemId=4915) with the same issue on the MVC CodePlex site. The comments to that issue offer the same solution.
patridge
This appears to be set up by default within Global.asax.cs in VS2010 when you create an empty MVC2 project.
patridge