Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock AuthenticateAsync on AspNetCore.Authentication.Abstractions

i have an action on a controller which calls

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

i'm trying to mock this result in a unit test like so

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

however that throws an InvalidOperationException

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

what is the correct way to mock this method?

like image 371
ryanthescot Avatar asked Oct 31 '17 14:10

ryanthescot


1 Answers

That 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 IServiceProvider RequestServices property.

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

Mock the service provider to return a mocked IAuthenticationService and you should be able to 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);

//...
like image 86
Nkosi Avatar answered Nov 15 '22 07:11

Nkosi