想在测试用例中不使用 WebApplicationFactory
,直接使用 TestServer
,TestServer
的构造函数需要传参 IWebHostBuilder
的实例, 如果能通过 WebApplication
创建 IWebHostBuilder
会更方便,请问是否可以实现?
IWebHostBuilder builder = new WebHostBuilder();
var testServer = new TestServer(builder);
var httpClient = testServer.CreateClient();
var response = await httpClient.GetAsync("/dapr/subscribe");
response.StatusCode.Should().Be(HttpStatusCode.OK);
通过下面的代码解决了
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
await app.StartAsync();
var httpClient = app.GetTestClient();
var response = await httpClient.GetAsync("/");
Console.WriteLine(await response.Content.ReadAsStringAsync());
response.StatusCode.Should().Be(HttpStatusCode.OK);