我有简单的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.
是否有一种测试区域初始化逻辑的好方法?
答案 0 :(得分:4)
临时解决方法:
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()
我不喜欢这种方法,但现在想不出更好的解决方案 欢迎提出意见和建议......