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 );
}
}
The preceding test simulates the context of a user who has logged on with a user name;
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 );
}