I'm trying to understand how to do integration tests on ASP.NET Core 6 web API controllers. I've tried following all the guides, SO posts and recommendations I could find but for some reason I keep hitting errors that aren't mentioned in the guides.
EventControllerTests.cs
namespace UnitTests.ProjectToBeTested.Controllers
{
public class EventControllerTests
{
[Fact]
public async Task EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync()
{
// Arrange
var application = new WebApplicationFactory<Program>();
var client = application.CreateClient();
...
ProjectToBeTested.csproj
...
<ItemGroup>
<InternalsVisibleTo Include="IntegrationTests" />
</ItemGroup>
...
This throws the following when running the test:
Message: System.InvalidOperationException : No method 'public static IHostBuilder CreateHostBuilder(string[] args)' or 'public static IWebHostBuilder CreateWebHostBuilder(string[] args)' found on 'Program'. Alternatively, WebApplicationFactory`1 can be extended and 'CreateHostBuilder' or 'CreateWebHostBuilder' can be overridden to provide your own instance.
Stack Trace: WebApplicationFactory
1.CreateWebHostBuilder() WebApplicationFactory
1.EnsureServer() WebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers) WebApplicationFactory
1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) WebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options) WebApplicationFactory
1.CreateClient() EventControllerTests.EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync() line 17 --- End of stack trace from previous location ---
This SO post shows up as a possible solution but is using pre-6 using a Startup class. What would the .NET 6 solution be?
If I instead follow the "Basic tests with the default WebApplicationFactory"-guide I can't even build the solution because of the test class constructor throwing
Error CS0051 Inconsistent accessibility: parameter type 'WebApplicationFactory' is less accessible than method 'EventControllerTests.EventControllerTests(WebApplicationFactory)' IntegrationTests C:\...\EventControllerTests.cs
Startup.cs
in an ASP.NET 6 Minimal API – UrgaProgram.cs
look like? – UrgaProgram.cs
– Urgadotnet new webapi
and a unit test withdotnet new xunit
. I addedMicrosoft.AspNetCore.Mvc.Testing
to the test project and was able to create an application with the code you posted. I did encounter problems when I created the projects through Jetbrains Rider – Urga