单元测试写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 ...
随机推荐
- [转]JVM调优总结:一些概念
JVM调优总结:一些概念 原文出处: pengjiaheng 数据类型 Java虚拟机中,数据类型可以分为两类:基本类型和引用类型.基本类型的变量保存原始值,即:他代表的值就是数值本身:而引用类型的变 ...
- skiing
package noj_skiing; import java.util.*; import java.math.*; public class Main { public static void m ...
- Ajax 密码验证
var names = $("names");var pwds = $("pwds");var ts1 = $("ts1");var ts2 ...
- bzoj2565: 最长双回文串
manacher之后乱搞 #include <iostream> #include <cstdio> #include <cstring> #include < ...
- js-JavaScript高级程序设计学习笔记2
第四章 变量.作用域和内存问题 1.ES变量包含两种不同数据类型的值--基本类型值(5种基本数据类型)和引用类型值(保存在内存中的对象,所有引用类型值都是Object的实例) 2.只能给引用类型值动态 ...
- HDFS源码分析:NameNode相关的数据结构
本文主要基于Hadoop1.1.2分析HDFS中的关键数据结构. 1 NameNode 首先从NameNode开始.NameNode的主要数据结构如下: NameNode管理着两张很重要的表: 1) ...
- 图像卷积、相关以及在MATLAB中的操作
图像卷积.相关以及在MATLAB中的操作 2016年7月11日 20:34:35, By ChrisZZ 区分卷积和相关 图像处理中常常需要用一个滤波器做空间滤波操作.空间滤波操作有时候也被叫做卷积滤 ...
- Discuz! x3.1 /utility/convert/index.php Code Execution Vul
catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Discuz! x3.1的插件/utility/convert/inde ...
- 数据结构算法C语言实现(二十)--- 6.3.1遍历二叉树
一.简述 二叉树的遍历主要是先序.中序.后序及对应的递归和非递归算法,共3x2=6种,其中后序非递归在实现上稍复杂一些.二叉树的遍历是理解和学习递归及体会栈的工作原理的绝佳工具! 此外,非递归所用的栈 ...
- codevs 3143 二叉树的序遍历
传送门 Description 求一棵二叉树的前序遍历,中序遍历和后序遍历 Input 第一行一个整数n,表示这棵树的节点个数. 接下来n行每行2个整数L和R.第i行的两个整数Li和Ri代表编号为i的 ...