【发布时间】:2021-04-20 06:47:16
【问题描述】:
我有一个存储库作为单独的项目(MyRepo),我使用这个存储库调用各种 grpc 服务。
我还没有部署 grpc 服务器,所以我在 localhost:5000 上运行它们以进行测试。
我得到的错误是:
无法建立连接,因为目标机器主动 拒绝了。 (本地主机:5000)
这显然是因为grpc服务器没有运行造成的。
如果我打开一个新的 Visual Studio 实例并启动 grpc 服务器,然后运行单元测试,一切正常。
我对单元测试 conecpt 很陌生,我想了解如何测试它。
我的代码:
public class StartupFixture
{
public ServiceProvider ServiceProvider { get; private set; }
private readonly IConfiguration configuration;
public StartupFixture()
{
var configBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
configuration = configBuilder.Build();
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<PlatformSettings>(configuration.GetSection("PlatformSettings"));
services.AddScoped<ICmsService, CmsService>();
services.AddScoped<IMyRepo, MyRepo>();
ServiceProvider = services.BuildServiceProvider();
}
}
public class UnitTestCmsPlatforms : IClassFixture<StartupFixture>
{
private ServiceProvider _serviceProvider;
public ImyRepo myRepo => _serviceProvider.GetService<IKoopRepo>();
public UnitTestCmsPlatforms(StartupFixture fixture)
{
_serviceProvider = fixture.ServiceProvider;
}
[Fact]
public async Task<List<Platforms>> Test1()
{
return await myRepo.CmsService.GetAllPlatformsAsync();
}
}
非常感谢任何帮助,谢谢!
【问题讨论】:
-
如果你想运行包含客户端和服务器(相互通信)的测试,我认为你最好的选择是实际查看 grpc-dotnet 本身的现有测试。在客户端的大量测试中(请参阅github.com/grpc/grpc-dotnet/tree/master/test/…),您实际上需要有一个正在运行的服务器 - 我相信这与您的情况非常相似。