WebApplicationFactory always return 404 (not found) for controllers calls in .net core 6
Asked Answered
W

1

6

In .net core 6, startup.cs has been removed, the integration testing I used before doesn't work anymore as is. I need to do an update.

In my API (program.cs), I added:

[assembly: InternalsVisibleTo("constructionCompanyAPI.IntegrationTests")]

and here is the Integration.Tests csproj:

csprojImage

I created a ConstructionCompanyControllersTests.cs like:

public class ConstructionCompanyControllerTests
{
    private HttpClient _client;

    public ConstructionCompanyControllerTests()
    {
        _client = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    var dbContextOptions = services
                    .SingleOrDefault(service => service.ServiceType == typeof(DbContextOptions<ConstructionCompanyDbContext>));

                    services.Remove(dbContextOptions);

                    services.AddDbContext<ConstructionCompanyDbContext>(options => options.UseInMemoryDatabase("ConstructionCompanyDb"));
                });
            })
            .CreateClient();
    }
    [Theory]
    [InlineData("?pageNumber=1&pageSize=10")]
    [InlineData("?pageNumber=1&pageSize=5")]
    public async Task GetAll_WithQueryParameters_ReturnsOkResult(string queryParams)
    {
        // act

        var response = await _client.GetAsync("/api/constructionCompany" + queryParams);

        // assert

        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
    }

When I launch the API, every thing works correctly, I'm to see my controller in Swagger and call the get with a code 200 returns.

So each time the test fails here:

var response = await _client.GetAsync("/api/constructionCompany" + queryParams);

The response always get a 404 error (not found).

Expected response.StatusCode to be HttpStatusCode.OK {value: 200}, but found HttpStatusCode.NotFound {value: 404}.

What should I do to make it works correctly?

Thanks

Edit: The Entire program.cs file:

program.cs

Weirick answered 11/8, 2022 at 9:15 Comment(2)
What is in Program? I would have expected that to be StartupDisconsolate
@Disconsolate I added the entire program.cs fileWeirick
W
10

I added "args" to the method and it worked

var builder = WebApplication.CreateBuilder(args);
Weirick answered 11/8, 2022 at 10:53 Comment(4)
dude...this little change and my day is saved :-) thxBrynhild
it saved me! I find the args provides: 1. env name, 2. content dir, 3. app name. I think the content dir works for this issueDisquieting
I was searching for hours :/Dimenhydrinate
This saved my day, thank you! This happened to me after converting my minimal API's to MVC controllers, but now by passing the args it works againDiverting

© 2022 - 2024 — McMap. All rights reserved.