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); }
本文转自today4king博客园博客,原文链接:http://www.cnblogs.com/jinzhao/archive/2011/07/18/2109887.html,如需转载请自行联系原作者