集成测试中的 DefaultHttpContext 测试身份验证

时间:2021-03-04 16:27:37

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

尝试运行一些集成测试并在我的单元和集成测试中使用 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 provider)

1 个答案:

答案 0 :(得分:1)

<块引用>

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

用此 thread 引用。