2

我有一个 NUnit 测试类,它启动一个在http://localhost:1070上运行的 ASP.NET Web 服务(使用 Microsoft.VisualStudio.WebHost.Server)

我遇到的问题是我想在 NUnit 测试中创建一个会话状态,该会话状态可由 localhost:1070 上的 ASP.NET Web 服务访问。
我做了以下,在NUnit Test里面可以成功创建会话状态,但是在调用web服务的时候就丢失了:

//Create a new HttpContext for NUnit Testing based on:
//http://blogs.imeta.co.uk/jallderidge/archive/2008/10/19/456.aspx
HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://localhost:1070/", ""), new HttpResponse(
     new System.IO.StringWriter()));

//Create a new HttpContext.Current for NUnit Testing
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
 HttpContext.Current, new HttpSessionStateContainer("",
  new SessionStateItemCollection(),
  new HttpStaticObjectsCollection(), 20000, true,
  HttpCookieMode.UseCookies, SessionStateMode.Off, false));

HttpContext.Current.Session["UserName"] = "testUserName";
testwebService.testMethod(); 

我希望能够获取在 ASP.NET Web 服务中的 Session["UserName"] 的 NUnit 测试中创建的会话状态:

[WebMethod(EnableSession=true)]
public int testMethod()
{
    string user; 

    if(Session["UserName"] != null)
    {
       user = (string)Session["UserName"];

      //Do some processing of the user
      //user is validated against with value stored in database
      return 1;
    }
    else
      return 0;
}

web.config 文件具有以下会话状态配置配置,并且希望继续使用 InProc 而不是 StateServer 或 SQLServer:

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="20"/> 
4

1 回答 1

0

您可以使用HttpContextBase,而不是使用实际的 HttpContext 类,然后模拟您的会话、响应、请求等。

于 2010-04-21T07:02:22.670 回答