If the request is authenticated, then the User property must be populated with the same principle.
public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations) { int userId = User.Identity.GetUserId<int>(); bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations); return Ok(isSavePlayerLocSaved ); }
for ApiController you can set the User property while placing the unit test. However, this extension method is looking for ClaimsIdentity , so you must provide one
The test will now look like
[TestMethod()] public void SavePlayerLocTests() { //Arrange //Create test user var username = "admin"; var userId = 2; var identity = new GenericIdentity(username, ""); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, username)); var principal = new GenericPrincipal(identity, roles: new string[] { }); var user = new ClaimsPrincipal(principal); // Set the User on the controller directly var controller = new TestApiController() { User = user }; //Act var actionResult = controller.SavePlayerLoc(GetLocationList()); var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>; //Assert Assert.IsNotNull(response); }
Nkosi source share