dotnet / dotnet/aspnetcore

Configure existing HttpClient using WebApplicationFactory (e.g. for named clients using IServiceCollection.AddHttpClient<T>)

Open
#38,883 6 comments 9 reactions 0 assignees View on GitHub
area-minimal area-mvc enhancement feature-mvc-testing
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is your feature request related to a problem? Please describe.

This is a duplicate of #5967 but because it was closed due to inactivity, I am creating a new one with more details and use cases.

I am trying to run tests against a Hot Chocolate (GraphQL) server and the Strawberry Shake GraphQL client, which uses `HttpClientFactory` with a named client.

I'd like to start my app in my tests using `Microsoft.AspNetCore.Mvc.Testing`, _and_ use the code generation features of Strawberry Shake to generate the GraphQL client. I can't, because Strawberry Shake uses the `HttpClientFactory`, and all of the methods required to build _or_ configure an HttpClient are internal in `WebApplicationFactory`.

Example of the code in my tests I'd like to have (simplified and inlined):

```c#
var services = new ServiceCollection();
// Here I cannot easily configure the client since it needs a custom HttpMessageHandler from TestServer
services
.AddHttpClient(GraphClient.ClientName, client => client.BaseAddress = _factory.Server.BaseAddress)
.ConfigurePrimaryHttpMessageHandler(_ => _factory.Server.CreateHandler());
services
// This is a library that depends on HttpClientFactory
.AddGraphClient()
// This is using HttpClientFactory internally
var graphClient = services.BuildServiceProvider().GetRequiredService();
```

### Describe the solution you'd like

It would be much simpler if instead of just having `CreateClient()`, I could also use `ConfigureClient(HttpClient)`.

e.g.:

```c#
.ConfigureHttpClient(client => _factory.ConfigureClient(client));
```

The code is mostly the same as is already inside `WebApplicationFactory`, however instead of making more properties and methods public, there would be a method to assist in cases where using HttpClientFactory is desirable.

### Additional context

While my use case (and the one from #5967) are because of external libraries, I believe making use of a pooled HttpClient factory can make sense for reusing existing code from internal libraries.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.