.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
相关产品推荐
相关产品推荐

