【问题标题】:How to generate Asp.net User identity when testing WebApi controllers测试 WebApi 控制器时如何生成 Asp.net 用户身份
【发布时间】:2017-01-11 05:04:28
【问题描述】:

我正在使用 Web API 2。在 web api 控制器中,我使用 GetUserId 方法使用 Asp.net Identity 生成用户 ID。

我必须为那个控制器编写 MS 单元测试。如何从测试项目中访问用户 ID?

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

Web API 控制器

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

Web API 控制器测试类

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

我尝试使用上述模拟方法。但它不起作用。从测试方法调用控制器时如何生成 Asp.net 用户身份?

【问题讨论】:

    标签: c# asp.net unit-testing asp.net-web-api asp.net-identity


    【解决方案1】:

    如果请求通过了身份验证,那么应该使用相同的原则填充 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多