我们在开发WEB项目的时候,一般应用逻辑跟ASPX页面是分离的项目。应用逻辑一般会是一个DLL组件项目。如果这个组件项目中A方法使用了Session、Cookie等信息的读写,则这个方法就很难写单元测试。
  但并不是写不出来,要写出来大致思路如下:

  目标: 
  构建一个测试的环境,把需要的Session、Cookie等信息初始化好。 这样才好做测试。而且这个构建的环境,不应该影响实际功能代码的编写。

  具体实现来说:

  我们要使用Mock技术,但就HttpContext来言,直接mock这个对象会有一个问题,它不具备Session的功能。这时候我们就需要用 Mock 技术来构造一个可以满足我们需要的环境的原理:这个Mock的机制如下:

  用反射机制,构造一个 HttpSessionState 对象(HttpSessionState类的构造函数是internal 的),然后把这个对象跟SimpleWorkerRequest 对象捆绑。

这样我们就可以 构建了一个满足自己需要的环境了,即 TestHttpContext 类。

  以下是两个类的实现:

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 24 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 is 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 only to support legacy ASP compatibility. ASP.NET 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 only to support legacy ASP compatibility. ASP.NET 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; }
}

}

}

这样我们在进行单元测试时就可以Mock掉Web下的Session,Cookie等对象。

例如:

[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, "读取用户ID错误!");
}

单元测试写cookie的更多相关文章

  1. TDD中的单元测试写多少才够?

    测试驱动开发(TDD)已经是耳熟能详的名词,既然是测试驱动,那么测试用例代码就要写在开发代码的前面.但是如何写测试用例?写多少测试用例才够?我想大家在实际的操作过程都会产生这样的疑问. 3月15日,我 ...

  2. 跨域写cookie

    假设a站想往b站写cookie,那么目前有两种方案,参考如下: 第一种(使用jsonp): a站js代码如下: $.ajax({ url: 'http://www.b.com/jsonp.jsp?do ...

  3. PHP 跨域写cookie

    实际工作中,类似这样的要求很多,比如说,我们有两个域名,我们想实现在一个域名登录后,能自动完成另一个域名的登录,也就是PASSPORT的功能. 我只写一个大概,为了测试的方便,先编辑hosts文件,加 ...

  4. asp.net,cookie,写cookie,取cookie

    Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...

  5. .NET,Cookie,写Cookie,取Cookie

    Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...

  6. 怎么写cookie

    html结构 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  7. asp.net,cookie,写cookie,取cookie(转载)

    Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...

  8. tomcat 8.5 及其 9.0 response写cookie 设置damain为 [.test.com] 出错 An invalid domain [.test.com] was specified for this cookie

    抛出异常: java.lang.IllegalArgumentException: An invalid domain [.test.com] was specified for this cooki ...

  9. SpringBoot单元测试携带Cookie

    由于我SpringBoot项目,集成了SpringSecurity,而Security框架使用Redis存储Session,所以,这里列出几个关键的类 org.springframework.sess ...

随机推荐

  1. 512M内存编译php出错

    make时错误如下 virtual memory exhausted: Cannot allocate memory make: *** [ext/fileinfo/libmagic/apprenti ...

  2. mysql查询时间戳和日期的转换

    mysql提供了两个函数: from_unixtime(time_stamp) -> 将时间戳转换为日期 unix_timestamp(date) -> 将指定的日期或者日期字符串转换为时 ...

  3. mysql优化基础

    唯一索引(unique index)强调唯一,就是索引值必须唯一. create unique index [索引名] on 表名 (列名);alter table 表名 add unique ind ...

  4. webuploader跨域上传

    浏览器在跨域请求前会发个options请求来验证是否跨域,所以后端再处理这个options请求时,要告诉浏览器一些信息. 也就是个header信息 header("Access-Contro ...

  5. python 内建类型

    ''' 数值 numbers 字符串 strings 列表 lists 字典 dictionaries 元组 tuples 文件 files 集合 sets ''' 1.1 序列的操作 所有序列类型都 ...

  6. 微信公众平台教程和SDK收集

    教程收集: 1.Senparc(.net) http://www.cnblogs.com/szw/archive/2013/05/14/weixin-course-index.html 2.方倍工作室 ...

  7. C#实体图片下载与批量下载(自动保存功能)

    新工作,第一个小任务,制作一个点击下载图片的功能.并提供批量下载操作.图片是字节流的形式,存放在数据库中的. 为了避免直接从数据库中,下载失败,会在本地保存一份. 进行压缩的是SharpZip这个压缩 ...

  8. iOS 简单的动画自定义方法(旋转、移动、闪烁等)

    #define kDegreesToRadian(x) (M_PI * (x) / 180.0) #define kRadianToDegrees(radian) (radian*180.0)/(M_ ...

  9. hdu 2010 - 水仙花数

    题意: 数学上有个水仙花数,他是这样定义的:"水仙花数"是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3.现在要求输出所有在m和n范围内的水仙花 ...

  10. linux 驱动入门4

    不吃苦中苦,难为人上人.努力,给老婆孩子提供个良好的生活居住环境.http://www.cnblogs.com/nan-jing/articles/5806399.html上文提到了如何创建proc节 ...