Skip to content

Commit

Permalink
feat: test Named HttpClient reuse by AddRefitClient (#1910)
Browse files Browse the repository at this point in the history
Signed-off-by: Derek Moore <[email protected]>
Co-authored-by: Chris Pulman <[email protected]>
  • Loading branch information
derekm and ChrisPulman authored Nov 6, 2024
1 parent a56e9d8 commit da64f1f
Showing 1 changed file with 41 additions and 4 deletions.
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

0 comments on commit da64f1f

Please sign in to comment.