Search code examples
unit-testingasp.net-mvc-5asp.net-identity

How do you stub User.Identity.GetUserId() in ASP MVC 5 (Microsoft.AspNet.Identity)


How do you stub User.Identity.GetUserId() in ASP MVC 5 (Microsoft.AspNet.Identity) for a unit test of a MVC5 Controller? GetUserId() is an extension, so I can't mock it directly. And I need to assign the Id before the test. It seems that you have to create a Claim and assign it to a GenericIdentity. But it seems like a lot to do for a unit test. Do you know of any alternatives?


Solution

  • Thank you very much for the idea. I am using NSubstitute. I don’t have neither Microsoft Fakes nor JustMock. So I ended stuffing claims directly to the GenericIdentity so I could control the value of the UserId:

    string username = "username";
    string userid = Guid.NewGuid().ToString("N"); //could be a constant
    
    List<Claim> claims = new List<Claim>{
        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username), 
        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)
    };
    var genericIdentity = new GenericIdentity("");
    genericIdentity.AddClaims(claims);
    var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { "Asegurado" });
    controllerContext.HttpContext.User = genericPrincipal;