How to trick AuthenticateAsync on AspNetCore.Authentication.Abstractions

I have an action on the controller that calls

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

I am trying to make fun of this result in unit test so

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

however, it throws an invalidoperation exception "No service for type" Microsoft.AspNetCore.Authentication.IAuthenticationService registered "

What is the correct way to mock this method?

+4
source share
1 answer

This 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);

goes through the property IServiceProvider RequestServices.

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

Discard your service provider to return the mocking IAuthenticationService, and you can fake your way through the test.

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

//...
+3
source

Source: https://habr.com/ru/post/1688464/


All Articles