如何在 AspNetCore.Authentication.Abstractions 上模拟 AuthenticateAsync

how to mock AuthenticateAsync on AspNetCore.Authentication.Abstractions

我在调用

的控制器上有一个动作
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

我正试图在这样的单元测试中模拟这个结果

httpContextMock.AuthenticateAsync(Arg.Any<string>()).Returns(AuthenticateResult.Success(...

然而抛出 InvalidOperationException

"No service for type 'Microsoft.AspNetCore.Authentication.IAuthenticationService' has been registered"

模拟此方法的正确方法是什么?

那个extension method

/// <summary>
/// Extension method for authenticate.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> context.</param>
/// <param name="scheme">The name of the authentication scheme.</param>
/// <returns>The <see cref="AuthenticateResult"/>.</returns>
public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string scheme) =>
    context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme);

经过 IServiceProvider RequestServices 属性.

/// <summary>
/// Gets or sets the <see cref="IServiceProvider"/> that provides access to the request's service container.
/// </summary>
public abstract IServiceProvider RequestServices { get; set; }

将服务提供商模拟为 return 一个模拟的 IAuthenticationService,您应该能够伪造自己的方式通过测试。

authServiceMock.AuthenticateAsync(Arg.Any<HttpContext>(), Arg.Any<string>())
    .Returns(Task.FromResult(AuthenticateResult.Success()));
providerMock.GetService(typeof(IAuthenticationService))
    .Returns(authServiceMock);
httpContextMock.RequestServices.Returns(providerMock);

//...