Loading

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

 

 

posted @ 2011-07-18 18:50  today4king  阅读(381)  评论(0编辑  收藏  举报