问题描述
我正在尝试对包含以下行的代码进行单元测试:
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:
User.Identity.GetUserId()
返回一个值.我一直在我的控制器设置中尝试以下操作:
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");
但它给出了NotSupportedException was unhandled by user code"的错误.我还尝试了以下方法:
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("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("Andrew");
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });
controllerContext.HttpContext.User = genericPrincipal;
基于我在 stackoverflow 上找到的一些代码,但这会返回相同的错误NotSupportedException was unhandled by user code".
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.
推荐答案
您无法设置 GetUserId 方法,因为它是一个扩展方法.相反,您必须在用户的 IIdentity 属性上设置名称.GetUserId 将使用它来确定 UserId.
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");
这篇关于我如何模拟 User.Identity.GetUserId()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!