Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: test Named HttpClient reuse by AddRefitClient #1910

Merged
merged 2 commits into from
Nov 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions Refit.Tests/HttpClientFactoryExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
using Microsoft.Extensions.Options;

namespace Refit.Tests;

using System.Globalization;
using System.Net.Http;
using System.Reflection;
using System.Text.Json;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Refit.Implementation;

using Xunit;

namespace Refit.Tests;

public class HttpClientFactoryExtensionsTests
{
class User { }
Expand Down Expand Up @@ -154,6 +160,37 @@ public void HttpClientSettingsCanBeProvidedStaticallyGivenTypeArgument()
);
}

[Fact]
public void ProvidedHttpClientIsUsedAsNamedClient()
{
var baseUri = new Uri("https://0:1337");
var services = new ServiceCollection();

services.AddHttpClient("MyHttpClient", client => {
client.BaseAddress = baseUri;
client.DefaultRequestHeaders.Add("X-Powered-By", Environment.OSVersion.VersionString);
});
services.AddRefitClient<IGitHubApi>(null, "MyHttpClient");

var sp = services.BuildServiceProvider();
var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient("MyHttpClient");

var gitHubApi = sp.GetRequiredService<IGitHubApi>();

var memberInfos = typeof(Generated).GetMember("RefitTestsIGitHubApi", BindingFlags.NonPublic);
var genApi = Convert.ChangeType(gitHubApi, (Type)memberInfos[0], CultureInfo.InvariantCulture);
var genApiProperty = genApi.GetType().GetProperty("Client")!;
var genApiClient = (HttpClient)genApiProperty.GetValue(genApi)!;

Assert.NotSame(httpClient, genApiClient);
Assert.Equal(httpClient.BaseAddress, genApiClient.BaseAddress);
Assert.Equal(baseUri, genApiClient.BaseAddress);
Assert.Contains(
new KeyValuePair<string, IEnumerable<string>>("X-Powered-By",
new[] { Environment.OSVersion.VersionString }), genApiClient.DefaultRequestHeaders);
}

class ClientOptions
{
public SystemTextJsonContentSerializer Serializer { get; set; }
Expand Down
Loading