我正在尝试为 token 管理 API 运行一些集成测试。 API 还需要运行 token 发行者 API。
总而言之,我的集成测试需要同时运行 IdentityServer4 Web/API 和管理 API。当我创建 TestServer
的两个实例时,它们似乎都以相同的 BaseAddress
(http://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);
}
注意: 我已经尝试过的事情:
- 添加
.UseUrls("http://localhost:5001")
以查看 TestServer 是否将在该端口上运行。 - 添加
serverName.BaseAddress = new Uri("http://localhost:5001");
以查看 TestServer 是否将在该端口上运行。
这些似乎都不会影响它。
最佳答案
我知道这是一个老问题,但我遇到了同样的问题。我认为诀窍是将从“服务器 1”获得的 HttpClient 注入(inject)“服务器 2”。
Test server does not open any real sockets, so running on different urls is a fictitious concept anyways. You can set BaseAddress to anything you want.
I assume your actual challenge is communicating with those test servers? Again, they don't open any real sockets, the only way to communicate with them is through their CreateClient API which creates an in-memory channel.
示例(.NET 核心):
//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);
关于c# - ASP.NET Core 运行两个 TestServer 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081905/