How to generate Asp.net User identity when testing WebApi controllers

只谈情不闲聊 提交于 2019-12-05 09:07:22

If the request is authenticated then the User property should 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 User property during arranging the unit test. That extension method however is looking for a ClaimsIdentity so you should provide one

The test would 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!