zoukankan      html  css  js  c++  java
  • Mock HttpContext in TDD的几种简单应用

    1)First case for an sample user:

        public class MockHttpContext : HttpContextBase
        {
            
    private readonly IPrincipal _user = new GenericPrincipal(
                     
    new GenericIdentity("username"), null /* roles */);

            
    public override IPrincipal User
            {
                
    get
                {
                    
    return _user;
                }
                
    set
                {
                    
    base.User = value;
                }
            }

            
    public MockHttpContext(string UserName)
            {
                _user 
    = new GenericPrincipal(new GenericIdentity(UserName), null);
            }
        }

     上面测试简单模拟了一个已经登录的带某用户名的用户的上下文;

    2)two function  for quick switch login state

            protected void LoginOut()
            {
                httpMock.Setup(h 
    => h.User.Identity.IsAuthenticated).Returns(false);
                DefaultHttpContext 
    = httpMock.Object;
                BaseController.ControllerContext 
    = new ControllerContext()
                                                       {
                                                           Controller 
    = BaseController,
                                                           RequestContext 
    =
                                                               
    new RequestContext(DefaultHttpContext, new RouteData())
                                                       };
                BaseController.SetCurrentUser(loginName);
            }
            
    protected void LoginIn()
            {
                httpMock.Setup(h 
    => h.User.Identity.IsAuthenticated).Returns(true);
                DefaultHttpContext 
    = httpMock.Object;
                BaseController.ControllerContext 
    = new ControllerContext()
                {
                    Controller 
    = BaseController,
                    RequestContext 
    =
                        
    new RequestContext(DefaultHttpContext, new RouteData())
                };
                BaseController.SetCurrentUser(loginName);
            }
    作者:KKcat
        
    个人博客:http://jinzhao.me/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    SysUtils.UpperCase、SysUtils.LowerCase 大小写转换
    Sql Server 2005 数据库备份还原后出现“受限制用户”问题的解决
    为什么要跪谢
    【基础】C#卸载快捷方式添加
    DataTable 复制 DataRow 出现 “该行已经属于另一个表”错误的解决办法
    将int型转化成五位字符串,前面用0填充
    C#嵌套类的使用方法及特性(转)
    net内存回收与Dispose﹐Close﹐Finalize方法(转)
    sqlhelper中文注释版(转)
    windows2003消息队列的安装
  • 原文地址:https://www.cnblogs.com/jinzhao/p/2109887.html
Copyright © 2011-2022 走看看