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/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    并发编程 19—— 显式的Conditon 对象
    JVM实用参数——新生代垃圾回收
    设计模式 8 —— 适配器和外观模式
    并发编程 18—— 使用内置条件队列实现简单的有界缓存
    并发编程 17—— Lock
    Spring 事务管理 01 ——
    并发编程 16—— 线程池 之 原理二
    并发编程 15—— 线程池 之 原理一
    并发编程 14—— 线程池 之 整体架构
    java.util.logging.Logger 使用详解
  • 原文地址:https://www.cnblogs.com/jinzhao/p/2109887.html
Copyright © 2011-2022 走看看