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/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Docker界面化管理
    搭建MQTT服务器(Docker版)
    VS Code Markdown文件实时预览
    Nginx直接处理接口请求,返回相应内容(带html标签)
    Docker(九): 安装MySQL主从复制
    feign的一个注解居然隐藏这么多知识!
    使用Magisk指令修改 ro.debuggable(不刷机)
    【钓鱼可用】文件名反转字符串
    android高级UI之贝塞尔曲线<下>--贝塞尔曲线运用:QQ消息气泡
    英文阅读技巧操练---Article 1:The Product-Minded Software Engineer《一》
  • 原文地址:https://www.cnblogs.com/jinzhao/p/2109887.html
Copyright © 2011-2022 走看看