簡體   English   中英

如何在MVC 3中測試區域注冊邏輯?

[英]How do I test area registration logic in MVC 3?

我有簡單的HttpApplication類:

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

        // register other stuff...
    }
}

我的單元測試初始化HttpApplication ,調用ApplicationStart並驗證應用程序啟動行為。

這種方法很有效,直到我必須整合MVC領域。 當單元測試調用AreaRegistration.RegisterAllAreas() ,會拋出以下異常:

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

是否有一種測試區域初始化邏輯的好方法?

臨時解決方法:

1)在MvcApplication中,公開虛方法RegisterAllAreas()

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

        // register other stuff...
    }

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

2)在規范中,實現代理:

[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)單獨測試區域AreaRegistration實現

4)從測試覆蓋范圍中排除MvcApplication.RegisterAllAreas()

我不喜歡這種方法,但現在想不出更好的解決方案。
歡迎提出意見和建議......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM