【发布时间】:2022-01-09 23:36:13
【问题描述】:
我正在为操作方法MethodUnderTest 编写单元测试(使用NUnit 和MOQ),该方法在内部使用HttpContext 来执行某些功能。我正在通过调用InitializeHostingEnvironment 来设置一个假的托管环境,我正在初始化会话,例如:
public static HttpSessionState InitializeSession()
{
var httpRequest = new HttpRequest("", "http://localhost/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
HttpContext.Current = httpContext;
HttpContext.Current.Items.Clear();
HttpSessionState session = (HttpSessionState)ReflectionHelper.Instantiate(typeof(HttpSessionState), new Type[] { typeof(IHttpSessionState) }, new FakeHttpSessionState());
HttpContext.Current.Items.Add("AspSession", session);
return session;
}
public static void InitializeHostingEnvironment(string userName, string password)
{
// lines of code
InitializeSession();
}
我从我的测试方法中调用InitializeHostingEnvironment(),如下所示:
public static void Test_MethodUnderTest()
{
InitializeHostingEnvironment(UN, PW);
MethodUnderTest(param1, param2, param3); -- getting exception while trying to execute this line
}
在尝试执行 MethodUnderTest(param1, param2, param3); 行时,我遇到了一个异常 - System.ArgumentNullException - Value cannot be null. Parameter name httpBrowserCapabilities。堆栈跟踪如下:
由于异常说 httpBrowserCapabilities 为空,我尝试在 InitializeSession() 方法中像 HttpContext.Current.Request.Browser = new HttpBrowserCapabilities(); 一样初始化它,但是现在,我遇到了另一个异常:
我现在该怎么办?我初始化HttpContext 的方式错了吗?请指教。
【问题讨论】:
-
为什么要测试连接器而不是连接结果?我认为您在定义级别误解了 UT
-
您可能有正当理由需要测试您正在测试的内容。但是您没有向我们展示错误。您向我们展示了抛出异常的位置,但您已经切断了实际错误。如果这些失败的测试真的表明代码中有错误怎么办?与其剪切和粘贴图片,不如复制文本。我们不需要整个堆栈跟踪,但至少需要开始 - 异常类型、消息以及它被抛出的位置。
标签: c# asp.net asp.net-mvc moq httpcontext