I'm trying to mock the User.Identity in my Api Controller test.
This is my api method:
[Route(Urls.CustInfo.GetCustomerManagers)]
public HttpResponseMessage GetCustomerManagers([FromUri]int groupId = -1)
{
var user = User.Identity.Name;
if (IsStaff(user) && groupId == -1)
{
return ErrorMissingQueryStringParameter;
}
...
}
I followed the suggestion in this post: Set User property for an ApiController in Unit Test to set the User property.
This is my test:
[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);
}
But when the test is run, the User property is always null.
I even tried moving the line for setting the CurrentPrincipal into the api method just before calling User.Identity, but it's still null.
What am I doing wrong? If this approach doesn't work for web api 2, what's the best way to simulate/mock the User property?
Thanks!