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

如何在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;

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....