加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

单元测试 – 单元测试Web Api 2模拟用户

发布时间:2020-12-14 18:32:11 所属栏目:资源 来源:网络整理
导读:我正试图在我的Api控制器测试中模拟User.Identity. 这是我的api方法: [Route(Urls.CustInfo.GetCustomerManagers)] public HttpResponseMessage GetCustomerManagers([FromUri]int groupId = -1) { var user = User.Identity.Name; if (IsStaff(user) group
我正试图在我的Api控制器测试中模拟User.Identity.

这是我的api方法:

[Route(Urls.CustInfo.GetCustomerManagers)]
    public HttpResponseMessage GetCustomerManagers([FromUri]int groupId = -1)
    {
        var user = User.Identity.Name;
        if (IsStaff(user) && groupId == -1)
        {
            return ErrorMissingQueryStringParameter;
        }
        ...
    }

我按照这篇文章中的建议:Set User property for an ApiController in Unit Test来设置User属性.

这是我的测试:

[TestMethod]
    public void User_Without_Group_Level_Access_Call_GetCustomerManagers_Should_Fail()
    {
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Bob","Passport"),new[] {"managers"}); 
        var response = m_controller.GetCustomerManagers();

        Assert.AreEqual(HttpStatusCode.BadRequest,response.StatusCode);
    }

但是在运行测试时,User属性始终为null.

我甚至尝试在调用User.Identity之前移动用于将CurrentPrincipal设置为api方法的行,但它仍然为null.

我究竟做错了什么?如果这种方法不适用于web api 2,那么模拟/模拟User属性的最佳方法是什么?

谢谢!

解决方法

您可以在ControllerContext.RequestContext.Principal中设置用户:
controller.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity("Bob",new[] {"managers"});

或者速记等同物:

controller.User = new GenericPrincipal(new GenericIdentity("Bob",new[] {"managers"});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读