【发布时间】:2014-06-11 05:54:35
【问题描述】:
我试图在我的 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 方法中,但它仍然为空。
我做错了什么?如果这种方法不适用于 web api 2,模拟/模拟 User 属性的最佳方法是什么?
谢谢!
【问题讨论】:
标签: unit-testing asp.net-web-api mocking asp.net-web-api2