我有一个.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
    }
}

现在我的目标是现在使用我的配置数据库中的AddGbContent,因为这向真实的数据库显示,而我想用InMemory数据库覆盖它.

AppFixture中的正常情况我想覆盖此附件.但由于FastEndpoints和我的设置中的WebAppliationBuilder覆盖了IWebHostBuilder,因此这是不可覆盖的(这两个get都被调用了).

如何做到这一点?

推荐答案

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

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问题提供一个复制项目.我非常乐意为您修好它.

Csharp相关问答推荐

将序列化的IasyncESYS上传到Azure Blob存储的最佳方法是什么

C# Json重新初始化动态类型

为什么我在PuppeteerSharp中运行StealthPlugin时会出现错误?

我可以 suppress 规则CS 9035一次吗?

一种安全的方式来存储SSH凭证(MAUI/C#应用程序)

NumPy s fftn in C#with pythonnet'

需要澄清C#的Clean Architecture解决方案模板的AuditableEntityInterceptor类

. NET JSON属性自定义所需逻辑

有没有办法使.NET 6应用程序在特定的.NET 6运行时版本上运行

C#XmlSerializer-输出控制新行的多个XML片段

如何使用C#获取FireStore中的列表输出文档

在C#中,将两个哈希集连接在一起的时间复杂度是多少?

为什么@rendermode Interactive Auto不能在.NET 8.0 Blazor中运行?

如何使用用于VS代码的.NET Maui扩展在我的iOS/Android设备或模拟器上进行调试?

如何允许数组接受多个类型?

在.NET8中如何反序列化为私有字段?

我是否应该注销全局异常处理程序

如何在特定时间间隔运行多个后台任务?

将列表转换为带有逗号分隔字符串形式的值的字典

如何对正方形格线进行对角分组