Unit Test Write Cookie

Source: Internet
Author: User

When we develop Web projects, the general application logic and ASPX pages are separate projects. The application logic will typically be a DLL component project. This method is difficult to write unit tests if the A method uses a session, cookie, and other information to read and write in this component project.
But not to write out, to write out the general idea is as follows:

Goal:
Build a test environment to initialize the required session, cookie, and so on. So it's good to do the test. And the environment of this build should not affect the writing of actual function code.

For specific implementations:

We're going to use the mock technique, but in HttpContext, a direct mock of this object has a problem, and it doesn't have the function of the session. At this point we need to use mock techniques to construct an environment that satisfies our needs: The mechanism of this mock is as follows:

Using the reflection mechanism, constructs a HttpSessionState object (the constructor of the HttpSessionState class is internal), and then binds the object to the SimpleWorkerRequest object.

This allows us to build an environment that satisfies our needs, namely the Testhttpcontext class.

The following are implementations of the two classes:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Web.SessionState;
Using System.Web;
Using System.Threading;
Using System.Globalization;
Using System.Collections.Specialized;
Using System.Collections;
Using System.IO;
Using System.Web.Hosting;
Using System.Reflection;

Namespace Testnamespace
{
public class Testhttpcontext
{
Private Const string contextkeyaspsession = "Aspsession";
Private HttpContext context = NULL;
Private Testhttpcontext (): Base () {}
Public Testhttpcontext (bool issecure)
: This ()
{
Mysessionstate mystate = new Mysessionstate (Guid.NewGuid (). ToString ("N"),
New Sessionstateitemcollection (), New Httpstaticobjectscollection (),
5, True, Httpcookiemode.useuri, Sessionstatemode.inproc, false);



TextWriter tw = new StringWriter ();
HttpWorkerRequest wr = new SimpleWorkerRequest ("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", TW);
This.context = new HttpContext (WR);
HttpSessionState state = Activator.CreateInstance (
typeof (HttpSessionState),
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | Bindingflags.createinstance,
Null
New object[] {mystate},
CultureInfo.CurrentCulture) as HttpSessionState;
This.context.items[contextkeyaspsession] = State;
HttpContext.Current = This.context;
}

Public HttpContext Context
{
Get
{
return this.context;
}
}

Private Class Workerrequest:simpleworkerrequest
{
private bool issecure = false;
Public workerrequest (String page, string query, TextWriter output, bool issecure)
: Base (page, query, Output)
{
This.issecure = issecure;
}

public override bool Issecure ()
{
return this.issecure;
}
}
}
public sealed class Mysessionstate:ihttpsessionstate
{
const int max_timeout = 24 * 60; Timeout cannot exceed hours.

String pId;
Isessionstateitemcollection Psessionitems;
Httpstaticobjectscollection pstaticobjects;
int ptimeout;
BOOL Pnewsession;
HttpCookieMode Pcookiemode;
Sessionstatemode PMode;
BOOL Pabandon;
BOOL Pisreadonly;

Public mysessionstate (String ID,
Isessionstateitemcollection Sessionitems,
Httpstaticobjectscollection StaticObjects,
int timeout,
BOOL NewSession,
HttpCookieMode Cookiemode,
Sessionstatemode mode,
BOOL isreadonly)
{
PId = ID;
Psessionitems = Sessionitems;
Pstaticobjects = StaticObjects;
Ptimeout = timeout;
Pnewsession = newsession;
Pcookiemode = Cookiemode;
PMode = mode;
Pisreadonly = isreadonly;
}


public int Timeout
{
get {return ptimeout;}
Set
{
if (value <= 0)
throw new ArgumentException ("Timeout value must be greater than zero.");

if (Value > Max_timeout)
throw new ArgumentException ("Timout cannot be greater than" + max_timeout. ToString ());

Ptimeout = value;
}
}


public string SessionID
{
get {return pId;}
}


public bool Isnewsession
{
get {return pnewsession;}
}


Public Sessionstatemode Mode
{
get {return pMode;}
}


public bool Iscookieless
{
get {return Cookiemode = = Httpcookiemode.useuri;}
}


Public HttpCookieMode Cookiemode
{
get {return pcookiemode;}
}


//
Abandon marks the session as abandoned. The Isabandoned property was used by the
Session state module to perform the abandon work during the ReleaseRequestState event.
//
public void Abandon ()
{
Pabandon = true;
}

public bool Isabandoned
{
get {return Pabandon;}
}

//
Session.LCID exists legacy ASP compatibility. ASP. Developers should use
Page.lcid instead.
//
public int LCID
{
get {return Thread.CurrentThread.CurrentCulture.LCID;}
set {Thread.CurrentThread.CurrentCulture = Cultureinfo.readonly (new CultureInfo (value));}
}


//
Session.CodePage exists legacy ASP compatibility. ASP. Developers should use
Response.ContentEncoding instead.
//
public int CodePage
{
Get
{
if (httpcontext.current! = null)
return HttpContext.Current.Response.ContentEncoding.CodePage;
Else
return Encoding.Default.CodePage;
}
Set
{
if (httpcontext.current! = null)
HttpContext.Current.Response.ContentEncoding = encoding.getencoding (value);
}
}


Public Httpstaticobjectscollection StaticObjects
{
get {return pstaticobjects;}
}


public object This[string Name]
{
get {return psessionitems[name];}
set {Psessionitems[name] = value;}
}


public Object This[int Index]
{
get {return psessionitems[index];}
set {Psessionitems[index] = value;}
}


public void Add (string name, object value)
{
Psessionitems[name] = value;
}


public void Remove (string name)
{
Psessionitems.remove (name);
}


public void RemoveAt (int index)
{
Psessionitems.removeat (index);
}


public void Clear ()
{
Psessionitems.clear ();
}

public void RemoveAll ()
{
Clear ();
}



public int Count
{
get {return psessionitems.count;}
}



Public Nameobjectcollectionbase.keyscollection Keys
{
get {return psessionitems.keys;}
}


Public IEnumerator GetEnumerator ()
{
return Psessionitems.getenumerator ();
}


public void CopyTo (Array items, int index)
{
foreach (object o in Items)
Items. SetValue (o, index++);
}


public Object SyncRoot
{
get {return this;}
}


public bool IsReadOnly
{
get {return pisreadonly;}
}


public bool IsSynchronized
{
get {return false;}
}

}

}

This allows us to mock off objects such as Session,cookie under the web when we are doing unit testing.

For example:

[TestMethod ()]
public void Testgetuserid ()
{
Testhttpcontext mock = new Testhttpcontext (false);
System.Web.HttpContext context = mock. Context;
Context. session["UserId"] = 1245;

Assert.AreEqual (Long. Parse (context. session["UserId"]. ToString ()), 1245, "Read User ID Error!" ");
}

Unit Test Write Cookie

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.