Integration testing your ASP.NET Core API's shouldn't be too difficult thanks to the Microsoft.AspNetCore.Mvc.Testing package.
First add the package to your project:
dotnet add package Microsoft.AspNetCore.Mvc.Testing
Now you can inject the WebApplicationFactory<TEntryPoint> in your tests:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ApiTests:IClassFixture<WebApplicationFactory<Api.Startup>> | |
{ | |
public HttpClient Client { get; } | |
public ApiTests(WebApplicationFactory<Api.Startup> fixture) | |
{ | |
Client = fixture.CreateClient(); | |
} | |
[Fact] | |
public async Task Test() | |
{ | |
var request = new HttpRequestMessage(); | |
var response = await Client.SendAsync(request); | |
response.EnsureSuccessStatusCode(); | |
} | |
} | |
You can tweak the configuration by inheriting from the WebApplicationFactory and use one of the overrides:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class SelfHostedApi : WebApplicationFactory<Api.Startup> | |
{ | |
protected override IHostBuilder CreateHostBuilder() | |
{ | |
return Host.CreateDefaultBuilder().ConfigureWebHostDefaults(builder => | |
builder.UseStartup<Api.Startup>()); | |
} | |
protected override void ConfigureWebHost(IWebHostBuilder builder) | |
{ | |
builder.ConfigureServices(services => | |
{ | |
}); | |
} | |
} |