单元测试 – 单元测试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"});

相关文章

vue阻止冒泡事件 阻止点击事件的执行 <div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些