测试WebApi控制器时如何生成Asp.net用户身份 [英] How to generate Asp.net User identity when testing WebApi controllers

查看:74
本文介绍了测试WebApi控制器时如何生成Asp.net用户身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Web API 2. In web api controller I have used GetUserId method to generate user id using Asp.net Identity.

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

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控制器

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控制器测试类

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

我尝试使用类似上面的模拟方法.但这是行不通的.从测试方法调用到控制器时,如何生成Asp.net用户身份?

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?

推荐答案

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

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

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

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

测试现在看起来像

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

这篇关于测试WebApi控制器时如何生成Asp.net用户身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆