Search code examples
c#minimal-apisfast-endpoints

How to do Integration Testing with FastEndpoints and .NET 8 WebApplicationBuilder?


I have a .NET 8 minimal API setup:

var builder = WebApplication.CreateBuilder(args);
var app = builder.ConfigureApp();
app.Run();

// Reference for Testing Purposes of FastEndpoints
namespace BeeHive.Api
{
    public abstract class Program;
}


public static WebApplication ConfigureApp(this WebApplicationBuilder builder)
{
    builder = builder
        .ConfigureConfiguration()
        .ConfigureLogging()
        .ConfigureSwagger()
        .ConfigureDatabase()
        .ConfigureApi();

    var app = builder.Build();

    app.UseSwaggerConfig()
        .UseApi()
        .UseDatabase();
    
    return app;
}

Now I use the FastEnpoinds:

https://fast-endpoints.com/docs/integration-unit-testing#service-registration

With that I have a simple setup of my integration test:

public class PingPongEndpointTest(BeeHiveApiFixture app) : TestBase<BeeHiveApiFixture>
{
    [Fact]
    public async Task PingPongEndpoint_ExpectedBehaviour()
    {
        var (httpResponse, dataResponse) = await app.Client.POSTAsync<PingPongEndpoint, PingPongEndpointRequest, PingPongEndpointResponse>(
            new()
            {
                Text = "Test"
            });

        httpResponse.StatusCode.Should().Be(HttpStatusCode.OK);
        dataResponse.ReversedText.Should().Be("tseT");
    }
}

public class BeeHiveApiFixture : AppFixture<Program>
{
    protected override void ConfigureApp(IWebHostBuilder a)
    {
        // Doesnt overwrite the WebApplicationBuilder
    }
}

Now my goal is to now use the AddDbContext from my ConfigureDatabase, because this shows to a real database instead I want to overwrite this with a InMemory Database.

Normaly in the AppFixture I would like to overwrite this behauviour. But with being and IWebHostBuilder in the override from FastEndpoints and a WebApplicationBuilder in my setup this isnt overrideable (both get's called).

How to do this?


Solution

  • this is how you'd typically replace the db context for tests:

    public class BeeHiveApiFixture : AppFixture<Program>
    {
        protected override void ConfigureServices(IServiceCollection services)
        {
            // remove the real db context configuration
            var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<MyDbContext>));
            if (descriptor != null)
                services.Remove(descriptor);
            
            //add a test db context
            services.AddDbContext<MyDbContext>(o => o.UseInMemoryDatabase("TestDB"));
        }
    }
    

    if that doesn't seem do it, please provide a repro project via the github issue you created. will be more than glad to fix it up for you.