单元测试 – 如何在ASP MVC 5(Microsoft.AspNet.Identity)中存储User.Identi

如何在ASP MVC 5(Microsoft.AspNet.Identity)中存储User.Identity.GetUserId(),以进行MVC5控制器的单元测试? GetUserId()是一个扩展名,所以我不能直接模拟它.我需要在测试之前分配Id.

您似乎必须创建一个声明并将其分配给GenericIdentity.但是,单元测试看起来好像很多.你知道任何替代品吗?

解决方法

非常感谢你的想法.我正在使用NSubstitute.我没有Microsoft Fakes和JustMock.所以我结束了直接对GenericIdentity的索赔,所以我可以控制UserId的值:

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("");
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity,new string[] { "Asegurado" });
controllerContext.HttpContext.User = genericPrincipal;

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。