나는 인터페이스를 사용하는 것이 최선의 선택 일 것이라고 동의하지만 때로는 기존 시스템을 바꿀 수없는 경우도 있습니다. 여기 내 프로젝트 중 하나에서 방금 만든 코드를 사용하면 원하는 결과를 얻을 수 있습니다. 예쁘거나 훌륭한 솔루션에서 가장 멀리 떨어져 있지만, 코드를 변경할 수 없다면 일을 끝내야합니다.
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