我正在尝试为Application_Start
上加载的ASPNET HttpApplication测试'插件'。
代码是这样的:
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
{1}}允许这样做。
我尝试过以下各种变体,每次都会遇到路障。
[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的模型的测试。
答案 0 :(得分:7)
经过一些细心的思考和一些反思:),我想出了解决自己问题的方法让我走了:
[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
对象,足以测试依赖于此的代码块。