在一些方法中使用了HttpContext.Current.
class Log
{
public void Save()
{
_name = HttpContext.Current.User.Identity.Name; //需要用到Current.User
_logDal.Save(this); //_logDal负责持久化
}
}
然后写一个测试方法
[TestMethod]
public void TestInsertLog()
{
Log log = new Log();
log.Save();
}
运行测试,报未找到对象的错误,因为HttpContext.Current这时为空,修改测试如下:
[TestInitialize()] //这里使用TestInitialize,而不是ClassInitialize是因为,测试类中可能同时存在多个测试方法,而每个测试方法都需要HttpContext.Current,而HttpContext.Current在一个测试方法执行完毕后,又成为了null,所以使用TestInitialize,以保证每次执行一个方法时,都构造一遍HttpContext.Current;
public void MyTestInitialize()
{
HttpContext.Current = new HttpContext(new HttpRequest("", "http://localhost", ""),
new HttpResponse(new StringWriter(new StringBuilder()))); //模拟HttpContext.Current;
HttpContext.Current.User = new MyPrincipal(); //虚拟的Principle对象,以供HttpContext.Current.User.Identity.Name
}
public class MyPrincipal : IPrincipal //模拟的IPrincipal接口
{
public bool IsInRole(string role)
{
return true;
}
public IIdentity Identity
{
get { return new MyIdentity(); }
}
}
public class MyIdentity : IIdentity
{
public string Name
{
get { return "单元测试用户"; }
}
public string AuthenticationType
{
get { return "单元测试用户"; }
}
public bool IsAuthenticated
{
get { return true; }
}
}
模拟HttpContext.Current单元测试
本文介绍了一种在单元测试中模拟HttpContext.Current的方法,通过创建模拟的HttpContext和Principal对象,解决了测试过程中因HttpContext.Current为空而导致的问题。

被折叠的 条评论
为什么被折叠?



