单元测试时如何模拟HttpContext


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值