You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7 XUnit项目无法找到PostgreSqlTestcontainer类求助

解决Testcontainers v3.0.0中找不到PostgreSqlTestcontainer类的问题

你遇到的问题根源在于Testcontainers从v3.0.0版本开始,将数据库特定的容器实现拆分到了独立的NuGet包中——主Testcontainers包仅包含核心通用功能,PostgreSqlTestcontainer类并不在主包内。

解决步骤:

  • 安装PostgreSQL专用的Testcontainers包:
    使用.NET CLI执行命令:

    dotnet add package Testcontainers.PostgreSql --version 3.0.0
    

    也可以通过NuGet包管理器搜索Testcontainers.PostgreSql并安装对应版本。

  • 在测试代码中添加命名空间引用:

    using Testcontainers.PostgreSql;
    
  • 更新后的.csproj文件会新增如下包引用:

    <PackageReference Include="Testcontainers.PostgreSql" Version="3.0.0" />
    

简单使用示例:

public class PostgreSqlTests : IAsyncLifetime
{
    private readonly PostgreSqlTestcontainer _postgresContainer = new PostgreSqlTestBuilder()
        .WithImage("postgres:15-alpine")
        .WithDatabase("testdb")
        .WithUsername("testuser")
        .WithPassword("testpass")
        .Build();

    public Task InitializeAsync()
    {
        return _postgresContainer.StartAsync();
    }

    public Task DisposeAsync()
    {
        return _postgresContainer.StopAsync();
    }

    [Fact]
    public async Task TestDatabaseConnection()
    {
        await using var connection = new NpgsqlConnection(_postgresContainer.GetConnectionString());
        await connection.OpenAsync();
        Assert.Equal(System.Data.ConnectionState.Open, connection.State);
    }
}

内容的提问来源于stack exchange,提问作者Learning AWS and PostgreSQL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:35:09