【发布时间】:2014-11-24 23:01:03
【问题描述】:
我正在为 MVC 5 Web 应用程序编写单元测试。我从我的测试中嘲笑了HttpContext.Current。
当运行以下代码时,测试httpSessionStateAfter throw
System.AggregateException:发生一个或多个错误。
----> System.NullReferenceException : 对象引用未设置为对象的实例。
这仅在我运行单元测试时发生。当应用程序运行此工作正常。 我正在使用 Nunit 2.6.3 和 reshaper 测试运行器。
var httpSessionStateBefour = System.Web.HttpContext.Current.Session;
var Person= await Db.Persons.FirstOrDefaultAsync();
var httpSessionStateAfter = System.Web.HttpContext.Current.Session;
如何解决这个问题?
这就是我模拟 HttpContext 的方式
HttpContext.Current = Fakes.FakeHttpContext();
HttpContext.Current.Session.Add("IsUserSiteAdmin", true);
HttpContext.Current.Session.Add("CurrentSite", null);
public static class Fakes
{
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof (HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] {typeof (HttpSessionStateContainer)},
null)
.Invoke(new object[] {sessionContainer});
return httpContext;
}
}
【问题讨论】:
-
你的问题到底是什么?
-
@Tragedian 我猜“为什么
httpSessionStateAfter为空,而httpSessionStateBefour不是?” -
您使用的是哪个单元测试框架?你确定它支持执行上下文吗?例如,旧版本的 NUnit 对
await一无所知,因此它们无法配置延续。在 ASP.NET 应用程序中,延续是在 不同的 ThreadPool 线程上执行的,该线程配置了原始执行上下文 -
你在嘲笑
HttpContext.Current吗?请出示此代码。 -
Nunit 2.6.3 和 Reshaper 8
标签: c# asp.net-mvc unit-testing async-await