How do I test area registration logic in MVC 3?
Asked Answered
Y

1

6

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?

Yb answered 5/3, 2012 at 15:40 Comment(0)
Y
4

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…

Yb answered 5/3, 2012 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.