使用NUnit测试ASMX Web服务并传输会话状态

时间:2010-04-21 06:49:56

标签: asp.net nunit session-state httpcontext

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

我遇到的问题是我想在NUnit测试中创建一个可由localhost:1070上的ASP.NET Web服务访问的会话状态。
我已经完成了以下操作,并且可以在NUnit测试中成功创建会话状态,但在调用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"/> 

1 个答案:

答案 0 :(得分:0)

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