我同意其他人使用接口是最好的選擇,但有時候改變現有的系統是不可行的。這裏有一些代碼,我從我的一個項目中找到了一些代碼,這些代碼可以讓你找到你想要的結果。這是最美妙的解決方案,但如果你真的無法改變你的代碼,那麼它應該完成工作。
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
[TestFixture]
public class HttpContextCreation
{
[Test]
public void TestCache()
{
var context = CreateHttpContext("index.aspx", "http://tempuri.org/index.aspx", null);
var result = RunInstanceMethod(Thread.CurrentThread, "GetIllogicalCallContext", new object[] { });
SetPrivateInstanceFieldValue(result, "m_HostContext", context);
Assert.That(HttpContext.Current.Cache["val"], Is.Null);
HttpContext.Current.Cache["val"] = "testValue";
Assert.That(HttpContext.Current.Cache["val"], Is.EqualTo("testValue"));
}
private static HttpContext CreateHttpContext(string fileName, string url, string queryString)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var hres = new HttpResponse(sw);
var hreq = new HttpRequest(fileName, url, queryString);
var httpc = new HttpContext(hreq, hres);
return httpc;
}
private static object RunInstanceMethod(object source, string method, object[] objParams)
{
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var type = source.GetType();
var m = type.GetMethod(method, flags);
if (m == null)
{
throw new ArgumentException(string.Format("There is no method '{0}' for type '{1}'.", method, type));
}
var objRet = m.Invoke(source, objParams);
return objRet;
}
public static void SetPrivateInstanceFieldValue(object source, string memberName, object value)
{
var field = source.GetType().GetField(memberName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
if (field == null)
{
throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", memberName));
}
field.SetValue(source, value);
}
}
你可以嘲笑幾乎所有的HttpContextBase,但Cache屬性都不在其中。 HttpContextBase.Cache的類型是System.Web.Caching.Cache,它是密封的,在單元測試中不可用並且不可嘲弄... – chris166 2009-08-20 09:45:50