xunit-如何在单元测试中获取HttpContext.User.Identity [英] xunit - how to get HttpContext.User.Identity in unit tests

查看:41
本文介绍了xunit-如何在单元测试中获取HttpContext.User.Identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向我的控制器添加了一个方法,以从 HttpContext 中的JWT令牌获取用户ID.在我的单元测试中, HttpContext null ,因此出现异常.

I added a method to my controllers to get the user-id from the JWT token in the HttpContext. In my unit tests the HttpContext is null, so I get an exception.

我该如何解决该问题?有没有一种方法可以对 HttpContext 进行定量?

How can I solve the problem? Is there a way to moq the HttpContext?

这是将用户吸引到我的基本控制器中的方法

Here is the method to get the user in my base controller

protected string GetUserId()
{
    if (HttpContext.User.Identity is ClaimsIdentity identity)
    {
        IEnumerable<Claim> claims = identity.Claims;
        return claims.ToList()[0].Value;
    }

    return "";
}

我的一个测试看起来像这样

One of my tests look like this

[Theory]
[MemberData(nameof(TestCreateUsergroupItemData))]
public async Task TestPostUsergroupItem(Usergroup usergroup)
{
    // Arrange
    UsergroupController controller = new UsergroupController(context, mapper);

    // Act
    var controllerResult = await controller.Post(usergroup).ConfigureAwait(false);

    // Assert
    //....
}

推荐答案

在这种特殊情况下,确实不需要模拟 HttpContext .

There really is no need to have to mock the HttpContext in this particular case.

使用 DefaultHttpContext 并将完成测试所需的成员设置为完成

Use the DefaultHttpContext and set the members necessary to exercise the test to completion

例如

[Theory]
[MemberData(nameof(TestCreateUsergroupItemData))]
public async Task TestPostUsergroupItem(Usergroup usergroup) {
    // Arrange

    //...

    var identity = new GenericIdentity("some name", "test");
    var contextUser = new ClaimsPrincipal(identity); //add claims as needed

    //...then set user and other required properties on the httpContext as needed
    var httpContext = new DefaultHttpContext() {
        User = contextUser;
    };

    //Controller needs a controller context to access HttpContext
    var controllerContext = new ControllerContext() {
        HttpContext = httpContext,
    };
    //assign context to controller
    UsergroupController controller = new UsergroupController(context, mapper) {
        ControllerContext = controllerContext,
    };

    // Act
    var controllerResult = await controller.Post(usergroup).ConfigureAwait(false);

    // Assert
    ....
}

这篇关于xunit-如何在单元测试中获取HttpContext.User.Identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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