我正在尝试测试加载在 ASPNET HttpApplication 上的“插件” Application_Start
。
代码是这样的:
private HttpApplication application;
public void Application_Start(object sender, EventArgs e)
{
this.application = sender as HttpApplication;
StartReportService();
}
private void StartReportService()
{
HandledReports = new SortedList<string, string>();
HandledReports.Add("myindex","myvalue");
}
public System.Collections.Generic.SortedList<String, String> HandledReports
{
get
{
application.Application.Lock();
var handledReports = (SortedList<String, String>)application.Application["handledReports"];
application.Application.UnLock();
return handledReports;
}
set
{
application.Application.Lock();
application.Application["handledReports"] = value;
application.Application.UnLock();
}
}
问题是我找不到测试的好方法,HttpApplicationState
主要是因为该HttpApplication.Application
属性不可覆盖,并且似乎没有允许这样做的HttpApplicationBase
类。System.Web.Abstractions
我尝试了以下变体,每次总是遇到障碍。
[TestMethod()]
public void StartReportService_ApplicationStateShouldContainMyIndex()
{
//No HttpApplicationBase in System.Web.Abstractions, must use Real Object
var application = new Mock<HttpApplication>();
//Real object does not have a property of type HttpApplicationStateBase so must use real one?
//var applicationStateBase = new Mock<HttpApplicationStateBase>();
//real one not creable so HACK get private constructor
var ctor = typeof(HttpApplicationState).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, new ParameterModifier[] { });
var applicationState = (HttpApplicationState)ctor.Invoke(new Object[] { });
//fails here, HttpApplication.Application not overridable
application.SetupProperty(x => x.Application, applicationState);
var plugin = HttpApplicationPlugin.HttpApplicationPluginInstance;
plugin.Application_Start(application.Object,null);
...evaluate result...
}
任何人都可以为我提供一些好的方法吗?这是对更多依赖于能够模拟运行的 HttpApplicationState 的第一个测试。