单元测试Web Api 2模拟用户

ozs*_*ent 7 unit-testing mocking asp.net-web-api asp.net-web-api2

我试图在我的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;
        }
        ...
    }
Run Code Online (Sandbox Code Playgroud)

我按照这篇文章中的建议:在单元测试中设置ApiController的User属性来设置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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢!

Los*_*ter 15

您可以将用户设置为ControllerContext.RequestContext.Principal:

controller.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"});
Run Code Online (Sandbox Code Playgroud)

或者速记等同物:

controller.User = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"});
Run Code Online (Sandbox Code Playgroud)

  • 以这种方式设置Principal后,未设置UserId.我需要设置它,因为我的测试系统中的逻辑基于Userid.例如,`User.Identity.Name`被填充("Bob")但不是'User.Identity.GetUserId()`. (2认同)