views:

270

answers:

1

I have a NUnit test class that starts an ASP.NET web service (using Microsoft.VisualStudio.WebHost.Server) which runs on http://localhost:1070

The problem I am having is that I want to create a session state within the NUnit test that is accessible by the ASP.NET web service on localhost:1070.
I have done the following, and the session state can be created successfully inside the NUnit Test, but is lost when the web service is invoked:

//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(); 

I want to be able to get the session state created in the NUnit test for Session["UserName"] in the ASP.NET web service:

[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;
}

The web.config file has the following configuration for the session state configuration and would like to remain using InProc than rather StateServer Or SQLServer:

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

Instead of using the actual HttpContext class, you can use HttpContextBase., and then mock your session, response, request and so on.

lasseeskildsen
The problem is that the session state for "Username" (in this case) is validated against values persistent in a database in testMethod(). I am not so sure whether using mock objects would work as this would cause the database validation process to fail, hence causing the unit test to fail. The issue is the session state is tied with the database end.
herbertyeung