AndrewPolland AndrewPolland - 15 days ago 8x
C# Question

How do I mock User.Identity.GetUserId()?

I am trying to unit test my code which includes the line:

UserLoginInfo userIdentity = UserManager.GetLogins(User.Identity.GetUserId()).FirstOrDefault();

I'm just stuck on one bit as I can't get:


to return a value. I have been trying the following in the set-up of my controller:

var mock = new Mock<ControllerContext>();
mock.Setup(p => p.HttpContext.User.Identity.GetUserId()).Returns("string");

But it gives an error of "NotSupportedException was unhandled by user code". I have also tried the following:

ControllerContext controllerContext = new ControllerContext();

string username = "username";
string userid = Guid.NewGuid().ToString("N"); //could be a constant

List<Claim> claims = new List<Claim>{
new Claim("", username),
new Claim("", userid)
var genericIdentity = new GenericIdentity("Andrew");
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });
controllerContext.HttpContext.User = genericPrincipal;

Based on some code I found on stackoverflow, but this returns the same error "NotSupportedException was unhandled by user code".

Any help as to how I proceed would be appreciated. Thanks.


You can't set up the GetUserId method because it's an extension method. Instead you'll have to set up the name on the user's IIdentity property. GetUserId will use this to determine the UserId.

var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("test_name");

See this for more info: