【发布时间】:2020-03-04 22:29:31
【问题描述】:
我们有几个 .NET Core 微服务/API,我们希望进行一些集成测试。 所以,我们按照教程进行操作,除了一种情况外,它工作正常。
假设我有 3 个 API,所以 3 个“TestServer”实例,每个都有自己的 HttpClient 来连接!
我展示了我创建 TestServer 的方式:
private TestServer SetupAPI<TStartup>(string path, string uri) where TStartup : class
{
string rootPath = Path.Join(_rootPath, "path");
var hostBuilder = WebHost.CreateDefaultBuilder()
.UseUrls(uri)
.UseIISIntegration()
//.ConfigureServices(services => services.AddSecurityHeaders())
.UseContentRoot(rootPath)
.UseEnvironment("Development")
.ConfigureAppConfiguration(cb =>
{
cb.AddJsonFile("appsettings.json", optional: false)
//.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
})
.UseStartup<TStartup>();
TestServer server = new TestServer(hostBuilder);
server.BaseAddress = new Uri(uri);
return server;
}
我展示了我是如何创建 HttpClient 的:
client = ArtistsServer.CreateClient();
client.BaseAddress = new Uri("http://localhost:5000");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
它工作得很好,但是当我尝试以这种方式创建一个新的 HttpClient 时,它失败了: HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("http://localhost:5000");
真正的问题是,一些微服务以这种方式创建自己的 HttpClient 以便与其他 API 通信!它们是通过 appsettings.json 文件设置的,并尝试连接到正常且真实的 http 服务器,而不是“TestServer”!
你有什么办法解决这个问题吗?
谢谢
【问题讨论】:
标签: c# asp.net-core asp.net-web-api integration-testing