Http messages can be sent through WebApplicationFactory in the following ways:
Example:
public class SampleTest : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public SampleTest(WebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task Test()
{
// Create an HttpClient with the base address of the web application
var client = _factory.CreateClient();
// Send an Http request using the HttpClient
var response = await client.GetAsync("/api/values");
// Assert the Http response
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("value1", content);
Assert.Contains("value2", content);
}
}
Example:
public class SampleTest : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public SampleTest(WebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task Test()
{
// Create a TestServer from the web application's IWebHostBuilder
var server = _factory.WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Test");
}).CreateServer();
// Create an HttpClient with the base address of the TestServer
var client = server.CreateClient();
// Send an Http request using the HttpClient
var response = await client.GetAsync("/api/values");
// Assert the Http response
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("value1", content);
Assert.Contains("value2", content);
}
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-01-12 11:00:00 +0000
Seen: 7 times
Last updated: Sep 11 '22