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/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Mac 卸载MySql的方法
    关于mysql的wait_timeout参数 设置不生效的问题
    linux下利用nohup后台运行jar文件包程序
    MySql创建视图
    spring mvc获取header
    Spring Data Jpa 查询返回自定义对象
    Caused by: org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must end with the ';' delimiter.
    eclipse Reference 功能之——项目之间的引用
    Mac 在启动eclipse时 Failed to load JavaHL Library解决方法
    MySQL Workbench update语句错误Error Code: 1175.
  • 原文地址:https://www.cnblogs.com/jinzhao/p/2109887.html
Copyright © 2011-2022 走看看