现在的位置: 首页 > 综合 > 正文

Mock HttpContext in TDD的几种简单应用

2012年12月15日 ⁄ 综合 ⁄ 共 1791字 ⁄ 字号 评论关闭

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);
        }

 

 

抱歉!评论已关闭.