Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integration test for ASP.NET Core 6 web API throws System.InvalidOperationException

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:  WebApplicationFactory1.CreateWebHostBuilder() WebApplicationFactory1.EnsureServer() WebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers) WebApplicationFactory1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) WebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options) WebApplicationFactory1.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

like image 276
r .r Avatar asked Jul 19 '26 18:07

r .r


1 Answers

Solution:

This was due to the Microsoft.AspNetCore.Mvc.Testing package for the test project using the wrong version (it was using version 5.*). Make sure that you use a version suitable for .NET 6. As of now there is a 6.0.0-rc.2.21480.10 version that works for me.

like image 184
r .r Avatar answered Jul 21 '26 09:07

r .r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!