kvnallen
11/25/2016 - 12:44 AM

Mock User Controller Context

Mock User Controller Context

public static class ControllerExtensions
    {
        public static void MockCurrentUser(this ApiController controller, string userId, string username)
        {
            var identity = new GenericIdentity(username);
            identity.AddClaim(
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username));
            identity.AddClaim(
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId));

            var principal = new GenericPrincipal(identity, null);

            controller.ControllerContext = Mock.Of<HttpControllerContext>(ctx =>
                ctx.RequestContext == Mock.Of<HttpRequestContext>(http =>
                    http.Principal == principal));
                    
            controller.Request = new HttpRequestMessage();
            controller.Request.SetConfiguration(new HttpConfiguration());
        }
    }