相关疑难解决方法(0)

我如何模拟User.Identity.GetUserId()?

我正在尝试对我的代码进行单元测试,其中包括以下行:

UserLoginInfo userIdentity = UserManager.GetLogins(User.Identity.GetUserId()).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

因为我无法得到,我只是被困在一点上:

User.Identity.GetUserId()
Run Code Online (Sandbox Code Playgroud)

返回一个值.我一直在设置控制器时尝试以下操作:

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

但是它给出了"NotSupportedException未被用户代码处理"的错误.我也尝试过以下方法:

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;
Run Code Online (Sandbox Code Playgroud)

基于我在stackoverflow上找到的一些代码,但这会返回相同的错误"NotSupportedException未被用户代码处理".

任何有关我如何进行的帮助将不胜感激.谢谢.

.net c# unit-testing moq asp.net-mvc-5

30
推荐指数
3
解决办法
2万
查看次数

标签 统计

.net ×1

asp.net-mvc-5 ×1

c# ×1

moq ×1

unit-testing ×1