我正在使用Web API2。在Web api Controller 中,我已使用GetUserId方法使用Asp.net Identity生成用户ID。

我必须为该 Controller 编写MS单元测试。如何从测试项目访问用户ID?

我在下面附加了示例代码。

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 测试类
[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);
}

我尝试使用类似上面的模拟方法。但这不起作用。从测试方法调用到 Controller 时,如何生成Asp.net用户身份?

最佳答案

如果请求已通过身份验证,则应使用相同的原则填充User属性

public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations) {
    int userId = User.Identity.GetUserId<int>();
    bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations);
    return Ok(isSavePlayerLocSaved );
}

对于ApiController,可以在安排单元测试期间设置User属性。但是,该扩展方法正在寻找ClaimsIdentity,因此您应该提供一个

现在测试看起来像
[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);
}

关于c# - 测试Web Api Controller 时如何生成Asp.net用户身份,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41583073/

10-11 22:10
查看更多