如何在用moq和nunit测试web api控制器时模拟用户身份?

问题描述:

我想与用户身份设置为测试Web服务调用(假装的用户登录)如何在用moq和nunit测试web api控制器时模拟用户身份?

我检查了无数的职位和*的答案,但我并没有完全得到我想要的答案。

离我最近的就是这个。

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

而在这一点上,我相信我一定要设置controllercontext和上下文变量需要以某种方式喂养。

我见过很多关于MVC控制器的例子,但我找不到适用于ApiController的例子。有人可以澄清这一点吗?

谢谢!

这是我做我的项目: 对于ASP.NET网页API

this._userController.User = new ClaimsPrincipal(
       new ClaimsIdentity(
        new List<Claim> 
        { 
         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1234"), 
         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "[email protected]"), 
         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#[email protected]") 
        }) 
       ); 

这是.NET的核心网络API:

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] 
      { 
       new Claim(ClaimTypes.NameIdentifier, "testId"), 
       new Claim(ClaimTypes.Name, "testName") 
      })); 

     this.controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext() 
     { 
      HttpContext = new DefaultHttpContext() { User = user } 
     }; 

让我知道,如果有帮助或不。

+0

感谢这篇文章,我会测试并给你一个更新! – rlee923

+0

我已经尝试了您的建议,并且已添加到声明标识中的声明项目既未通过RequestContext.Principal.Identity.Name也未通过User.Identity.Name(即未设置名称值)进行检查。检查身份下的索赔是否是标准做法? – rlee923

+0

感谢Hung,您的.net核心web api帮助我解决了这个问题。 – Neville

Awww,它很简单。

var identity = new GenericIdentity("bcd"); 

Controller.User = new GenericPrincipal(identity, null); 

原来这部分不需要嘲笑用户,你只需要设置你正在调用的控制器的用户ID。