How to generate Asp.net User identity when testing

2019-04-29 11:45发布

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?

1条回答
Animai°情兽
2楼-- · 2019-04-29 12:12

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);
}
查看更多
登录 后发表回答