How Mock JWT token in XUnit tests for Controller in WebApplicationFactory<Program>

Viewed 53

I am trying to test my controller by doing HttpClient requests.

I found that implementation for WebApplicationFactory:

public class PlaygroundApplication : WebApplicationFactory<Program>
{
    private readonly string _environment;

    public PlaygroundApplication(string environment = "Development")
    {
        _environment = environment;
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseEnvironment(_environment);       
        // Add mock/test services to the builder here
        builder.ConfigureServices(services =>
        {
            services.AddScoped(sp =>
            {
                // Replace SQLite with in-memory database for tests
                return new DbContextOptionsBuilder<DataBaseName>()
                .UseInMemoryDatabase("Tests")
                .UseApplicationServiceProvider(sp)
                .Options;
            });
        });

        return base.CreateHost(builder);
    }
}

And I do test in this way:

private HttpClient _client;
private PlaygroundApplication _application;
public AccountControllerTests()
{
    _application = new PlaygroundApplication();
    _client = _application.CreateClient();
}

[Fact]
public async Task Create_ShallReturnStatusOk()
{
    var user = new UserRegisterBasicDto();
    user.Email = "usertest2@test.com";
    user.ProviderType = ProviderTypes.Google;
    using var response = await _client.PostAsJsonAsync("/api/account/register", user);

    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

I am trying now test controllers which have Authorize attribute for example:

[Authorize(Roles = "User")]
[Authorize(Policy = "IsConfirmed")]

In program I am adding Authentication in this way:

service.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = "Bearer";
    o.DefaultScheme = "Bearer";
    o.DefaultChallengeScheme = "Bearer";
}).AddJwtBearer(cfg =>
{
    cfg.RequireHttpsMetadata = false;
    cfg.SaveToken = true;
    cfg.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = authenticationSettings.JwtIssuer,
        ValidAudience = authenticationSettings.JwtIssuer,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtKey)),
    };
});
service.AddAuthorization(o =>
{
    o.AddPolicy("IsNotConfirmed", b => b.RequireClaim("IsConfirmed", "False"));
});

I tried do something similar to this https://mazeez.dev/posts/auth-in-integration-tests but it doesn't want to work for JWT token

I want to Mock JWT token to be able test my controllers. ASP NET Core 6.0

Best if I could mock Claims from the method in the test.

0 Answers
Related