【问题标题】:How to user HttpContext AuthenticateAsync method in NUnit test case?如何在 NUnit 测试用例中使用 HttpContext AuthenticateAsync 方法?
【发布时间】:2021-02-03 08:59:40
【问题描述】:

我们正在为 Gmail 或 Microsoft 的外部登录使用 HttpContext Authenticate Async 方法。使用此 httpcontext 时登录和注册工作正常。但是当我们需要为此场景编写 NUnit 测试用例时,我无法初始化和设置声明标识。为以下场景编写代码

this.externalLoginController.ControllerContext = new ControllerContext();
        this.externalLoginController.ControllerContext.HttpContext = new DefaultHttpContext();
        var testScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
        var principal = new ClaimsPrincipal();
        principal.AddIdentity(new ClaimsIdentity(new[] {
        new Claim(ClaimTypes.Role, "Administrator"),
        new Claim(ClaimTypes.NameIdentifier, "test")
        }, testScheme));

设置httpcontext初始化后调用函数

 var result = await this.HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme).ConfigureAwait(false);

在这种情况下,面临“value cannot be null: Parameter(provider)”之类的问题。

我需要对 NUnit 测试用例使用 HttpContext 中的 Authenticate async 方法。

请指教。

谢谢, 沙拉湾。

【问题讨论】:

  • 其实我是想从controllerbase访问httpcontext方法,而不是actioncontext httpcontext。
  • 我已将此 A​​uthenticate async 方法移至 Service。所以我可以模拟服务方法。但是在这里我怎样才能返回验证结果?

标签: controller nunit httpcontext


【解决方案1】:

我使用下面的代码来模拟 AuthenticateAsync 方法并返回 AuthenticateResult。

    public class TestAuthenticationHandler : AuthenticationHandler<TestAuthenticationOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var authenticationTicket = new AuthenticationTicket(
                                         new ClaimsPrincipal(Options.Identity),
                                         new AuthenticationProperties(),
                                         this.Options.AuthenticationScheme);

        return Task.FromResult(AuthenticateResult.Success(authenticationTicket));
    }
}

以便我能够在单元测试中使用此方法并通过案例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多