单元测试写cookie
我们在开发WEB项目的时候,一般应用逻辑跟ASPX页面是分离的项目。应用逻辑一般会是一个DLL组件项目。如果这个组件项目中A方法使用了Session、Cookie等信息的读写,则这个方法就很难写单元测试。
但并不是写不出来,要写出来大致思路如下:
目标:
构建一个测试的环境,把需要的Session、Cookie等信息初始化好。 这样才好做测试。而且这个构建的环境,不应该影响实际功能代码的编写。
具体实现来说:
我们要使用Mock技术,但就HttpContext来言,直接mock这个对象会有一个问题,它不具备Session的功能。这时候我们就需要用 Mock 技术来构造一个可以满足我们需要的环境的原理:这个Mock的机制如下:
用反射机制,构造一个 HttpSessionState 对象(HttpSessionState类的构造函数是internal 的),然后把这个对象跟SimpleWorkerRequest 对象捆绑。
这样我们就可以 构建了一个满足自己需要的环境了,即 TestHttpContext 类。
以下是两个类的实现:
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等对象。
例如:
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的更多相关文章
- TDD中的单元测试写多少才够?
测试驱动开发(TDD)已经是耳熟能详的名词,既然是测试驱动,那么测试用例代码就要写在开发代码的前面.但是如何写测试用例?写多少测试用例才够?我想大家在实际的操作过程都会产生这样的疑问. 3月15日,我 ...
- 跨域写cookie
假设a站想往b站写cookie,那么目前有两种方案,参考如下: 第一种(使用jsonp): a站js代码如下: $.ajax({ url: 'http://www.b.com/jsonp.jsp?do ...
- PHP 跨域写cookie
实际工作中,类似这样的要求很多,比如说,我们有两个域名,我们想实现在一个域名登录后,能自动完成另一个域名的登录,也就是PASSPORT的功能. 我只写一个大概,为了测试的方便,先编辑hosts文件,加 ...
- asp.net,cookie,写cookie,取cookie
Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...
- .NET,Cookie,写Cookie,取Cookie
Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...
- 怎么写cookie
html结构 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...
- asp.net,cookie,写cookie,取cookie(转载)
Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一 ...
- 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 ...
- SpringBoot单元测试携带Cookie
由于我SpringBoot项目,集成了SpringSecurity,而Security框架使用Redis存储Session,所以,这里列出几个关键的类 org.springframework.sess ...
随机推荐
- 100200H
这是个bfs 首先建图,先从终点bfs求出每点距离,然后从起点开始,确定初始方向:某点和自己相邻距离比自己小1就是 然后就先贪心和上次一样的方向,如果不能走,就找出一个方向,把自己当前方向改掉,重复过 ...
- 网页提示[Not allowed to load local resource: file://XXXX]错误
网页通过http 访问时, 点击打开文件的link.在Chrome 中会报 Not allowed to load local resource: file// XXXX 的错误 <!--Add ...
- Java产生随机数
前言: 每一门程序设计语言基本都具有一个随机函数,而Java当中产生随机数的方式不拘一格.而且其中的Random工具类还有着更深入的应用,但本文仅对比3种产生随机数的方式,就不深入扩展分析其内部工具类 ...
- 【codevs1086】 栈
http://codevs.cn/problem/1086/ (题目链接) 题意 给出1~n总共n个数,对它们进行入栈出栈操作,问一共有多少种不同的方案. Solution 找规律手玩前5个1 2 5 ...
- .net config文件 配置类的集合
1,appconfig文件 <configSections> <section name="ToolConfig" type="DMTools.Tool ...
- poj3502 恶心题
巨恶心的一个题::>_<:: 题意:给出航班航线和大陆,找航线上距离大陆最远的某一点距离大陆边缘的距离 标准算法:二分答案,从大陆边界向外扩展,扩展出来的面积会覆盖航线.找出航线上最后被覆 ...
- 关于Unity3d粒子系统的小发现(天堂3技能释放)
导入系统给的粒子包,发现了一个问题:系统的粒子都有移动轨迹. 而自己新建的空粒子系统却没有这个功能.顺便也复习一下粒子系统. Particle System (粒子系统): Duration(持续时间 ...
- 【Beta版本】冲刺-Day7
队伍:606notconnected 会议时间:12月15日 目录 一.行与思 二.站立式会议图片 三.燃尽图 四.代码Check-in 一.行与思 张斯巍(433) 今日进展:修改界面,应用图标 明 ...
- Linux rsync网站目录同步功能的实现
实现目标: 172.16.1.64服务器上的/var/www/sw_service目录,与172.16.1.60服务器上的/var/www/sw_service目录实现同步, 即1.60主动向1.64 ...
- HTML5系列四(特征检测、Modernizr.js的相关介绍)
Modernizr:一个HTML5特征检测库 Modernizr帮助我们检测浏览器是否实现了某个特征,如果实现了那么开发人员就可以充分利用这个特征做一些工作 Modernizr是自动运行的,无须调用诸 ...