我如何模拟User.Identity.GetUserId()? [英] How do I mock User.Identity.GetUserId()?

查看:1753
本文介绍了我如何模拟User.Identity.GetUserId()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想单元测试我的code,其中包括该行:

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异常是未处理由用户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;

根据一些code我发现计算器,但它返回相同的错误NotSupportedException异常是未处理由用户code。

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

任何帮助,以我如何进行将AP preciated。谢谢你。

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

推荐答案

您不能建立GetUserId方法,因为它是一个扩展方法。相反,你必须建立这个名字对用户的IIdentity的财产。 GetUserId将使用它来确定用户标识。

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");

有关详细信息,请参阅本:<一href="http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx">http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx

See this for more info: http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.111).aspx

这篇关于我如何模拟User.Identity.GetUserId()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆