首页 文章

ASP.NET Core运行两个TestServer进行集成测试

提问于
浏览
5

我正在尝试为令牌管理API运行一些集成测试 . API还要求令牌颁发者API正在运行 .

总之,我的集成测试需要同时运行IdentityServer4 Web / API和Management API . 当我创建 TestServer 的两个实例时,它们似乎都以相同的 BaseAddresshttp://localhost )结束 .

private readonly TestServer _identityTestServer;
private readonly TestServer _mgmtTestServer;
private readonly AppMgmtConfig _config;
private readonly AdminClient _adminClient;
private const string _certificatePassword = "test";

public AdminClientTests() : base(nameof(AdminClientTests))
{
    var connectionString = GetConnectionString();
    var dbSettings = new DbSettings(connectionString);

    Environment.SetEnvironmentVariable("IdentityServer4ConnString",
        dbSettings.IdentityServerConnectionString);
    Environment.SetEnvironmentVariable("CertificatePassword", _certificatePassword);

    _identityTestServer = new TestServer(new WebHostBuilder()
        .UseStartup<USBIdentityServer.Startup>()
        .UseEnvironment("IntegrationTest"));
    USBIdentityServer.Program.InitializeDatabase(_identityTestServer.Host);

    _mgmtTestServer = new TestServer(new WebHostBuilder()
        .UseStartup<IdentityServer4.Management.Startup>()
        .UseEnvironment("IntegrationTest"));

    _config = GetConfig();
    _adminClient = new AdminClient(_config);
}

NOTE: 我已经尝试过的事情:

  • 添加 .UseUrls("http://localhost:5001") 以查看TestServer是否将在该端口上运行 .

  • 添加 serverName.BaseAddress = new Uri("http://localhost:5001"); 以查看TestServer是否将在该端口上运行 .

这些似乎都没有影响它 .

1 回答

  • 0

    我知道这是一个老问题,但我遇到了同样的问题 . 我认为诀窍是将你从“服务器1”获得的HttpClient注入“服务器2” .

    示例(.NET Core):

    //Start and configure server 1.
    IWebHostBuilder server1 = new WebHostBuilder()
     .UseStartup < Project1.Startup > ()
     .UseKestrel(options => options.Listen(IPAddress.Any, 80))
     .UseConfiguration(new ConfigurationBuilder()
      .AddJsonFile("appsettings_server1.json")
      .Build()
     );
    
    TestServer testServer1 = new TestServer(server1);
    
    //Get HttpClient that's able to connect to server 1.
    HttpClient client1 = server1.CreateClient();
    
    IWebHostBuilder _server2 = new WebHostBuilder()
     .UseStartup < Project2.Startup > ()
     .ConfigureTestServices(
      services => {
       //Inject HttpClient that's able to connect to server 1.
       services.AddSingleton(typeof(HttpClient), client1);
      })
     .UseKestrel(options => options.Listen(IPAddress.Any, 81))
     .UseConfiguration(new ConfigurationBuilder()
      .AddJsonFile("appsettings_server2.json")
      .Build()
     );
    
    TestServer testServer2 = new TestServer(server2);
    

相关问题