diff --git a/tests/ReC.Tests/Client/RecClientTestBase.cs b/tests/ReC.Tests/Client/RecClientTestBase.cs new file mode 100644 index 0000000..c34a6e9 --- /dev/null +++ b/tests/ReC.Tests/Client/RecClientTestBase.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using ReC.Client; + +namespace ReC.Tests.Client; + +public abstract class RecClientTestBase : IDisposable +{ + private readonly WebApplicationFactory _factory; + private readonly ServiceProvider _serviceProvider; + + protected RecClientTestBase() + { + var apiContentRoot = LocateApiContentRoot(); + + _factory = new WebApplicationFactory() + .WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + builder.UseContentRoot(apiContentRoot); + }); + + _ = _factory.CreateClient(); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(_factory.Services.GetRequiredService()); + + services.AddRecClient(client => + { + client.BaseAddress = new Uri("http://localhost"); + }); + + services.AddHttpClient(ReCClient.ClientName) + .ConfigurePrimaryHttpMessageHandler(() => _factory.Server.CreateHandler()); + + _serviceProvider = services.BuildServiceProvider(); + } + + protected IServiceProvider ServiceProvider => _serviceProvider; + + protected IConfiguration Configuration => _factory.Services.GetRequiredService(); + + protected (ReCClient Client, IServiceScope Scope) CreateScopedClient() + { + var scope = _serviceProvider.CreateScope(); + var client = scope.ServiceProvider.GetRequiredService(); + return (client, scope); + } + + public void Dispose() + { + _serviceProvider.Dispose(); + _factory.Dispose(); + } + + private static string LocateApiContentRoot() + { + var current = new DirectoryInfo(AppContext.BaseDirectory); + while (current is not null) + { + var candidate = Path.Combine(current.FullName, "src", "ReC.API"); + if (File.Exists(Path.Combine(candidate, "appsettings.json"))) + return candidate; + + current = current.Parent; + } + + throw new DirectoryNotFoundException("Could not locate src/ReC.API content root from the test base directory."); + } +} diff --git a/tests/ReC.Tests/ReC.Tests.csproj b/tests/ReC.Tests/ReC.Tests.csproj index ded8021..08ca4a7 100644 --- a/tests/ReC.Tests/ReC.Tests.csproj +++ b/tests/ReC.Tests/ReC.Tests.csproj @@ -12,6 +12,7 @@ + @@ -21,7 +22,9 @@ + +