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/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    接口测试(基础知识)
    MapReduce的方式进行HBase向HDFS导入和导出
    HBase的JavaAPI操作
    Maven中settings.xml的配置项说明
    Eclipse使用Maven创建普通Java工程时错误:Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:RELEASE from any of the configured repositories.
    ip 子网掩码 网关 DNS
    IP地址,子网掩码、默认网关,DNS理论解释
    IP地址,子网掩码,默认网关,路由,形象生动阐述
    Hive的JDBC使用&并把JDBC放置后台运行
    Hive中自定义函数
  • 原文地址:https://www.cnblogs.com/jinzhao/p/2109887.html
Copyright © 2011-2022 走看看