Saturday, March 18, 2023
Functional Test a dotnet core Web API
#dotnet-core #functional-tests #integration-tests #visual-studio #web-api
This article is published at GitHub.You can raise issues, create pull requests or even fork the content...its open source.
In this article, you will learn how to functional test a dotnet core Web API project with an SQL database using Visual Studio and xUnit.
The following prerequisites will be required to complete this tutorial:
Open a dotnet core Web API project in Visual Studio.
Right click on the Solution, and then select Add > New Project....
Search for xunit, and then select xUnit Test Project, and then select Next.
Enter the following values in the Configure your new project window, and then select Next.
Parameter | Value |
---|---|
Project Name | Monitored.FunctionalTests |
Location | Location of your choice |
Enter the following values in Additional information, and then select Create.
Parameter | Value |
---|---|
Framework | .NET 6.0 (Long-term support) |
In Visual Studio, select Tools > Nuget Package Manager > Package Manager Console.
Enter the following.
Install-Package Microsoft.AspNetCore.Mvc.Testing -Version 6.0.14
Add the following code to the program.cs
class after app.Run
in the Web Api project.
public partial class Program { }
Right click on the Test Project, and then select Add > Project Reference....
Tick the Web API Project, and then select OK.
In the test project, add the following class CustomWebApplicationFactory
into a new Base
folder, replacing {YourConnectionString}
with your connection string.
public class CustomWebApplicationFactory<TProgram>
: WebApplicationFactory<TProgram> where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var dbContextDescriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<MonitoredAPIDataContext>));
services.Remove(dbContextDescriptor);
var dbConnectionDescriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbConnection));
services.Remove(dbConnectionDescriptor);
// Create open SqlConnection so EF won't automatically close it.
services.AddSingleton<DbConnection>(container =>
{
var connection = new SqlConnection("{YourConnectionString}");
connection.Open();
return connection;
});
services.AddDbContext<MonitoredAPIDataContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlServer(connection);
});
});
builder.UseEnvironment("Development");
}
}
Add the following class WeatherForecastScenarios
into the root of the test project.
public class WeatherForecastScenarios : IClassFixture<CustomWebApplicationFactory<Program>>
{
private readonly HttpClient _client;
private readonly CustomWebApplicationFactory<Program> _factory;
public WeatherForecastScenarios(CustomWebApplicationFactory<Program> factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task Get_get_filtered_weather_forecasts_and_response_ok_status_code()
{
// Act
var response = await _client.GetAsync("WeatherForecast?take=10&skip=0");
// Assert
response.EnsureSuccessStatusCode();
}
}
The final test project should look like the following.
In Visual Studio, select Test, and then Test Explorer.
In the Test Explorer, select the button.
Once the tests have run, you will see that all tests pass.
All my articles are written and managed as Markdown files on GitHub.
Please add an issue or submit a pull request if something is not right on this article or you have a comment.
If you'd like to simply say "thanks", then please send me a so the rest of Twitter can see how awesome my work is.