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?
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
ASP.NET Identity is Microsoft's user management library for ASP.NET. It includes functionality such as password hashing, password validation, user storage, and claims management. It usually also comes with some basic authentication, bringing its own cookies and multi-factor authentication to the party.
ASP.NET Identity can be used with all ASP.NET frameworks, such as ASP.NET Web Forms , MVC, Web Pages, Web API etc.ASP.NET Identity has been developed with some major security features like Two-Factor Authentication, Account Lockout, and Account Confirmation etc.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With