Skip to content

MinimalApiHostBuilderFactory not working when Program has Services.AddHttpClient #114

Open
@vgoranski

Description

Describe the bug
When using MinimalApiHostBuilderFactory.GetHostBuilder<Program>() and Program.cs has builder.Services.AddHttpClient() it seems that the test server is not created and injected HttpClient in the test class has BaseAddress = null

To Reproduce
Program.cs

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// The line that causes the bug
builder.Services.AddHttpClient("test");

builder.Services.AddControllers();

var app = builder.Build();

app.Map("/hello", () => "Hello world");
app.MapDefaultControllerRoute();

await app.RunAsync();

public class HomeController
{
    public IActionResult Index() => new ContentResult { Content = "Hello world" };
}

MinimalApiTest.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Xunit.DependencyInjection.AspNetCoreTesting;

namespace Xunit.DependencyInjection.Test.AspNetCore;

public class MinimalApiTest(HttpClient httpClient)
{
    [Fact]
    public async Task MinimalApiRouteResponseTest()
    {
        var responseText = await httpClient.GetStringAsync("/hello");
        Assert.Equal("Hello world", responseText);
    }

    public class Startup
    {
        public IHostBuilder CreateHostBuilder() => MinimalApiHostBuilderFactory.GetHostBuilder<Program>()
            .ConfigureHostConfiguration(builder =>
                builder.AddInMemoryCollection([KeyValuePair.Create(HostDefaults.EnvironmentKey, "Testing")]));
    }
}

Expected behavior
builder.Services.AddHttpClient in Program.cs should not prevent the creation of the test server.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions