I am using Web API 2. In web api controller I have used GetUserId
method to generate user id using Asp.net Identity.
I have to write MS unit test for that controller. How can I access user id from test project?
I have attached sample code below.
Web API Controller
public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations)
{
int userId = RequestContext.Principal.Identity.GetUserId<int>();
bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations);
return Ok(isSavePlayerLocSaved );
}
Web API Controller Test class
[TestMethod()]
public void SavePlayerLocTests()
{
var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("admin");
var controller = new TestApiController();
var actionResult = controller.SavePlayerLoc(GetLocationList());
var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>;
Assert.IsNotNull(response);
}
I tried using mock method like above. But it is not working. How do I generate Asp.net User identity when I call from test method to controller?
If the request is authenticated then the User property should be populated with the same principle
for
ApiController
you can setUser
property during arranging the unit test. That extension method however is looking for aClaimsIdentity
so you should provide oneThe test would now look like