DEV Community

Łukasz Reszke
Łukasz Reszke

Posted on

Setting Up API Integration Tests With Authorization In .NET Core

Recently I’ve introduced integration tests in of .NET Core projects. It’s pretty simple as there’ great support from Microsoft.AspNetCore.Mvc.Testing and Microsoft.AspNetCore.TestHost nuget packages.
I’ve used XUnit together with packages mentioned. In my opinion it works best due to ClassFixtures and Collections that XUnit is providing.

Setting up Environment for Integration Tests
As I mentioned in previous section, I am using XUnit framework. It lets me create TestFixtures.

Test Fixtures are useful when you want to have different kind for sets, for example:

Tests using unauthenticated user
Tests using authenticated user
Tests using user that has no authorization for certain resource
Tests that check multitenancy mechanism
and so on.

`
public class TestFixture : IClassFixture>
{
protected readonly WebApplicationFactory Factory;
protected HttpClient Client;

public TestFixture(WebApplicationFactory<Startup> factory)
{
    Factory = factory;
    SetupClient();
}

protected static HttpContent ConvertToHttpContent<T>(T data)
{
    var jsonQuery = JsonConvert.SerializeObject(data);
    HttpContent httpContent = new StringContent(jsonQuery, Encoding.UTF8);
    httpContent.Headers.Remove("content-type");
    httpContent.Headers.Add("content-type", "application/json; charset=utf-8");

    return httpContent;
}

private void SetupClient()
{
    Client = Factory.WithWebHostBuilder(builder =>
    {
        /* I am telling builder to use appsettings.Integration,
        that is correctly set up in my DevOps pipeline */
        builder.UseEnvironment("Integration");
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.Integration.json")
            .Build();

        builder.ConfigureTestServices(services =>
        {
            /* setup whatever services you need to override, 
            its useful for overriding db context if you're using Entity Framework */
            var dbConnectionString = configuration.GetSection("ConnectionStrings")["TheConnectionString"];

            services.AddDbContext<DbContext>(optionsBuilder =>
            {
                optionsBuilder.UseSqlServer(dbConnectionString);
            });

        })
        .CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false
        });
    }
Enter fullscreen mode Exit fullscreen mode

`

The fixture implements IClassFixture. This lets us:

Modify Services configuration, for example changing DbContext’s connection string (might be useful with Integration testing)
Overriding some other services, for example Azure KeyVaults, if you’re using them for secrets management
Sets up TestServer (this comes with WebApplicationFactory)
Create http client
I’ve also included method that is serializing data to json and adds necessary headers.
It helps me since my integration tests are checking if our REST Api is working as expected.

Read more at https://lukaszcoding.com/2020/04/integration-testing-in-net-core/

Latest comments (0)