c# - 使用最小起订量和 nunit 测试 web api Controller 时如何模拟用户身份?

标签 c# asp.net-web-api2 moq

我想测试带有用户身份集的 web 服务调用(假装用户已登录)

我检查了很多帖子和 stackoverflow 的答案,但我没有完全得到我想要的答案。

我得到的最接近的是这个。

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 Controller 的示例,但我找不到适用于 ApiController 的示例。有人可以解释一下吗?

谢谢!

最佳答案

这是我为我的项目所做的: 对于 ASP.NET Web 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", "Test@test.com"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#Test@test.com")
                    })
                );

这是 .net 核心 web 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 }
        };

如果有帮助,请告诉我。

关于c# - 使用最小起订量和 nunit 测试 web api Controller 时如何模拟用户身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547144/

相关文章:

c# - 如何在 c#.net 中获取 javascript 确认弹出窗口值

c# - 当找到路由/url但没有找到它背后的资源时返回什么?

asp.net-mvc - MOQ:不能将 Moq.Mock 转换为 VB.Net 中的接口(interface)

c# - 模拟使用参数的函数

asp.net-mvc - 模拟 HttpPostedFileBase 和 InputStream 进行单元测试

c# - 在 PowerShell 上通过 Rest 获取自定义对象

c# - 反序列化对象的JSON数组,但是当数组包含1个对象时,数组被省略

c# - 如何使用 Delegate.CreateDelegate 而不是 Func<> 定义委托(delegate)?

asp.net-web-api2 - 操作参数的必需属性不起作用

c# - 在 Web Api 中使用 Postman 授权属性认证