Tôi đang viết bài kiểm thử đơn vị cho ứng dụng web MVC 5. Tôi đã chế nhạo thử nghiệm HttpContext.Current
. Khi chạy sau mã mẫu thử nghiệm httpSessionStateAfter
némHttpContext.Current is null after await (only in unit tests)
System.AggregateException: Một hoặc nhiều lỗi xảy ra.
----> System.NullReferenceException: Tham chiếu đối tượng không được đặt thành phiên bản của đối tượng.
Điều này chỉ xảy ra khi tôi chạy thử nghiệm đơn vị. Khi ứng dụng chạy công việc này tốt. Tôi đang sử dụng Nunit 2.6.3 với trình chạy thử nghiệm nhân bản.
var httpSessionStateBefour = System.Web.HttpContext.Current.Session;
var Person= await Db.Persons.FirstOrDefaultAsync();
var httpSessionStateAfter = System.Web.HttpContext.Current.Session;
Làm cách nào để khắc phục sự cố này?
Đây là cách tôi nhạo báng 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;
}
}
Câu hỏi của bạn chính xác là gì? –
@Tragedian Tôi đoán "tại sao' httpSessionStateAfter' không có nhưng 'httpSessionStateBefour' không phải là?" – DavidG
Bạn đang sử dụng khung kiểm thử đơn vị nào? Bạn có chắc nó hỗ trợ các ngữ cảnh thực thi không? Các phiên bản cũ hơn của NUnit chẳng hạn biết gì về 'await' để chúng không thể cấu hình việc tiếp tục. Trong các ứng dụng ASP.NET tiếp tục được thực hiện trên một thread * ThreadPool * khác nhau được cấu hình với bối cảnh thực hiện ban đầu –