如何使用 FastEndpoints 和 .Net 8 WebApplicationBuilder 进行集成测试?

问题描述 投票:0回答:1

我有一个 .net 8 最小 API 设置:

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;
}

现在我使用 FastEnpoints:

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

这样我就完成了集成测试的简单设置:

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
    }
}

现在我的目标是使用我的ConfigureDatabase 中的AddDbContext,因为这显示了一个真实的数据库,而不是我想用内存数据库覆盖它。

通常在 AppFixture 中我想覆盖此行为。但是,由于 FastEndpoints 中的being和IWebHostBuilder以及我的设置中的WebApplicationBuilder,这是不可重写的(两者都被调用)。

如何做到这一点?

c# minimal-apis fast-endpoints
1个回答
0
投票

这就是您通常替换测试的数据库上下文的方式:

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"));
    }
}

如果这似乎不起作用,请通过您创建的 github 问题提供一个重现项目。我们非常乐意为您解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.