gpt4 book ai didi

unit-testing - 单元测试Web Api 2模拟用户

转载 作者:行者123 更新时间:2023-12-04 05:11:20 26 4
gpt4 key购买 nike

我正在尝试在Api Controller测试中模拟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", "Passport"), new[] {"managers"});

或等效的速记:
controller.User = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"});

关于unit-testing - 单元测试Web Api 2模拟用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24155526/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com