在一些方法中使用了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; }
}
}