Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test area registration logic in MVC 3?

I have simple HttpApplication class:

public class MvcApplication : HttpApplication
{
    public void Application_Start()
    {
        // register areas
        AreaRegistration.RegisterAllAreas();

        // register other stuff...
    }
}

My unit tests initialise HttpApplication, invoke ApplicationStart and verify application start-up behaviour.

This approach worked well until I had to integrate MVC areas. When AreaRegistration.RegisterAllAreas() is invoked by a unit test, the following exception gets thrown:

System.InvalidOperationException: This method cannot be called during the application's pre-start initialization stage.

Is there a good approach for testing area initialisation logic?

like image 747
Arnold Zokas Avatar asked Mar 05 '12 15:03

Arnold Zokas


1 Answers

Temporary workaround:

1) In MvcApplication, expose virtual method RegisterAllAreas()

public class MvcApplication : HttpApplication
{
    public void Application_Start()
    {
        // register areas
        RegisterAllAreas();

        // register other stuff...
    }

    public virtual void RegisterAllAreas()
    {
        AreaRegistration.RegisterAllAreas();
    }
}

2) In specification, implement a proxy:

[Subject(typeof(MvcApplication))]
public class when_application_starts : mvc_application_spec
{
    protected static MvcApplication application;
    protected static bool areas_registered;

    Establish context = () => application = new MvcApplicationProxy();

    Because of = () => application.Application_Start();

    It should_register_mvc_areas = () => areas_registered.ShouldBeTrue();

    class MvcApplicationProxy : MvcApplication
    {
        protected override void RegisterAllAreas()
        {
            areas_registered = true;
        }
    }
}

3) Test AreaRegistration implementations individually

4) Exclude MvcApplication.RegisterAllAreas() from test coverage

I don't like this approach, but can't think of a better solution right now.
Ideas and comments are welcome…

like image 97
Arnold Zokas Avatar answered Sep 18 '22 19:09

Arnold Zokas