【问题标题】:DefaultHttpContext testing authentication in integration testsDefaultHttpContext 在集成测试中测试身份验证
【发布时间】:2021-03-04 16:27:37
【问题描述】:

尝试运行一些集成测试并在我的单元和集成测试中使用 DefaultHttpContext。有没有办法在 DefaultHttpContext 上调用 SignInAsync()

        var claims = new List<Claim>();
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties
        {
            AllowRefresh = true,
            IsPersistent = true,
            IssuedUtc = DateTime.UtcNow
        };

        await _controller.HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

由于某种原因,使用 DefaultHttpContext 时在上面运行会引发异常

System.ArgumentNullException:值不能为空。 (参数“提供者”) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider 提供程序)

【问题讨论】:

  • 您可以看到这个thread 可能会有所帮助。
  • 是的,这行得通。非常感谢。 @Yingiu 请发表您的评论作为答案。

标签: c# .net asp.net-core


【解决方案1】:

您可以通过创建派生自所用接口的类来手动创建假/模拟,也可以使用模拟框架(如Moq)。

引用此thread

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2020-08-04
    • 2019-03-28
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多