微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正试图在我的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"});

原文地址:https://www.jb51.cc/html/226043.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐