【发布时间】:2014-05-10 20:05:32
【问题描述】:
我正在尝试对包含以下行的代码进行单元测试:
UserLoginInfo userIdentity = UserManager.GetLogins(User.Identity.GetUserId()).FirstOrDefault();
我只是卡住了一点,因为我无法理解:
User.Identity.GetUserId()
返回一个值。我在控制器的设置中一直在尝试以下操作:
var mock = new Mock<ControllerContext>();
mock.Setup(p => p.HttpContext.User.Identity.GetUserId()).Returns("string");
但它给出了“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;
基于我在 stackoverflow 上找到的一些代码,但这会返回相同的错误“NotSupportedException 未被用户代码处理”。
任何关于我如何进行的帮助将不胜感激。谢谢。
【问题讨论】:
-
实现这一点的标准方法是创建一个新服务,即
IIdentity,它将您的代码从GetUserId扩展方法中抽象出来,并将其设置为对调用您@ 的代码的依赖项987654327@ -
刚刚意识到我原来的答案只适用于派生的 ApiControllers。使用派生控制器的选项更新了我的答案,以及适用于两者的第二种方法。
标签: c# .net unit-testing moq asp.net-mvc-5