我正在尝试为加载的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();
HandledReports.Add("myindex","myvalue");
}
public System.Collections.Generic.SortedList HandledReports
{
get
{
application.Application.Lock();
var handledReports = (SortedList)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();
//Real object does not have a property of type HttpApplicationStateBase so must use real one?
//var applicationStateBase = new Mock();
//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的函数.
好吧经过一些仔细的思考和一些反思:),我想出了解决我自己问题的方法让我走了:
[TestMethod()]
public void StartReportService_ApplicationStateShouldContainMyIndex()
{
HttpApplicationPlugin plugin=null;
HttpApplication app = null;
HttpApplicationState applicationState = null;
String tempDir = "";
try
{
#region "Create HttpApplication and ApplicationState"
//No HttpApplicationBase in System.Web.Abstractions, must use Real Object
app = new HttpApplication();
//real one not creatable so HACK get private constructor
var ctor = typeof(HttpApplicationState).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null, new Type[] { }, new ParameterModifier[] { });
applicationState = (HttpApplicationState)ctor.Invoke(new Object[] { });
//HACK in the state prop for testing
var stateProp = typeof(HttpApplication).GetField(
"_state", BindingFlags.Instance | BindingFlags.NonPublic);
stateProp.SetValue(app, applicationState);
#endregion
plugin = HttpApplicationPlugin.HttpApplicationPluginInstance;
plugin.Application_Start(application.Object,null);
本质上,您可以使用反射为您提供一个HttpApplication
对象,该HttpApplicationState
对象足以测试依赖于此的代码块.