【问题标题】:Testing ASMX webservice using NUnit and transferring session state使用 NUnit 测试 ASMX Web 服务并传输会话状态
【发布时间】:2011-02-10 11:18:32
【问题描述】:

我有一个 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"/> 

【问题讨论】:

  • 我不喜欢使用模拟对象,因为 Web 服务与数据库后端密切相关,并且会话状态值会根据存储的内容进行验证。

标签: asp.net nunit session-state httpcontext


【解决方案1】:

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

【讨论】:

  • 问题是“用户名”(在这种情况下)的会话状态是根据 testMethod() 中数据库中持久的值来验证的。我不太确定使用模拟对象是否会起作用,因为这会导致数据库验证过程失败,从而导致单元测试失败。问题是会话状态与数据库端相关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 2011-09-16
  • 2011-12-19
  • 2020-07-27
  • 1970-01-01
相关资源
最近更新 更多