为 .Net 单元测试设置 HttpContext

问题描述 投票:0回答:1

我正在为操作方法

NUnit
编写单元测试(使用
MOQ
MethodUnderTest
),该方法在内部使用
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
为空,我尝试在
HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
方法中像
InitializeSession()
一样初始化它,但现在,我遇到了另一个异常:

我现在应该做什么?我初始化的方式

HttpContext
是错误的吗?请指教。

c# asp.net asp.net-mvc moq httpcontext
1个回答
3
投票

我正在为 MethodUnderTest 方法编写单元测试(使用 NUnit 和 MOQ),该方法在内部使用 HttpContext 来执行某些功能。

对。不要那样做。控制器应该是访问 HttpContext 的唯一方法,并且它应该提取 MethodUnderTest 所需的数据并使用写入 HttpContext。

构建代码以使每个方法都有单一职责是编写可测试代码的基础。

© www.soinside.com 2019 - 2024. All rights reserved.