Skip to content

Commit

Permalink
use Xunit.DependencyInjection to update tests
Browse files Browse the repository at this point in the history
fix #41
  • Loading branch information
WeihanLi committed Oct 22, 2020
1 parent f337767 commit d30e351
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 77 deletions.
61 changes: 4 additions & 57 deletions OpenReservation.API.Test/APITestFixture.cs
Original file line number Diff line number Diff line change
@@ -1,74 +1,21 @@
using System;
using System.Net.Http;
using OpenReservation.Database;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WeihanLi.Common.Helpers;
using Xunit;

namespace OpenReservation.API.Test
{
/// <summary>
/// Shared Context https://xunit.github.io/docs/shared-context.html
/// </summary>
public class APITestFixture : IDisposable
public class APITestFixture
{
private readonly IWebHost _server;
public IServiceProvider Services { get; }

public HttpClient Client { get; }

public APITestFixture()
public APITestFixture(IServiceProvider serviceProvider, HttpClient httpClient)
{
var baseUrl = $"http://localhost:{NetHelper.GetRandomPort()}";
_server = WebHost.CreateDefaultBuilder()
.UseUrls(baseUrl)
.UseStartup<TestStartup>()
.Build();
_server.Start();
Services = serviceProvider;

Services = _server.Services;

Client = new HttpClient(new WeihanLi.Common.Http.NoProxyHttpClientHandler())
{
BaseAddress = new Uri($"{baseUrl}")
};
Client = httpClient;
// Add Api-Version Header
// Client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Version", "1.2");

Initialize();

Console.WriteLine("test begin");
}

/// <summary>
/// TestDataInitialize
/// </summary>
private void Initialize()
{
}

public void Dispose()
{
using (var dbContext = Services.GetRequiredService<ReservationDbContext>())
{
if (dbContext.Database.IsInMemory())
{
dbContext.Database.EnsureDeleted();
}
}

Client.Dispose();
_server.Dispose();

Console.WriteLine("test end");
}
}

[CollectionDefinition("APITestCollection")]
public class APITestCollection : ICollectionFixture<APITestFixture>
{
}
}
6 changes: 2 additions & 4 deletions OpenReservation.API.Test/Controllers/ControllerTestBase.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
using System;
using System.Net.Http;
using Xunit;

namespace OpenReservation.API.Test.Controllers
{
[Collection("APITestCollection")]
public class ControllerTestBase
public abstract class ControllerTestBase
{
protected HttpClient Client { get; }

protected IServiceProvider Services { get; }

public ControllerTestBase(APITestFixture fixture)
protected ControllerTestBase(APITestFixture fixture)
{
Client = fixture.Client;
Services = fixture.Services;
Expand Down
1 change: 1 addition & 0 deletions OpenReservation.API.Test/OpenReservation.API.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="$(DotNetCorePackageVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Xunit.DependencyInjection" Version="7.0.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
</ItemGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,55 @@
using Microsoft.AspNetCore.Builder;
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OpenReservation.API.Test.MockServices;
using OpenReservation.Common;
using OpenReservation.Database;
using OpenReservation.Events;
using OpenReservation.Services;
using WeihanLi.Common;
using WeihanLi.Common.Event;
using WeihanLi.Common.Helpers;
using WeihanLi.Redis;
using WeihanLi.Web.Authentication;
using WeihanLi.Web.Authentication.HeaderAuthentication;

namespace OpenReservation.API.Test
{
public class TestStartup
public class Startup
{
public TestStartup(IConfiguration configuration)
public void ConfigureHost(IHostBuilder hostBuilder)
{
Configuration = configuration;
}
var baseUrl = $"http://localhost:{NetHelper.GetRandomPort()}";

public IConfiguration Configuration { get; }
hostBuilder
.ConfigureWebHostDefaults(builder =>
{
builder.UseUrls(baseUrl);
builder.ConfigureServices((context, services) =>
{
services.TryAddSingleton<APITestFixture>();
services.TryAddSingleton(new HttpClient()
{
BaseAddress = new Uri(baseUrl)
});
ConfigureServices(services, context.Configuration);
});
builder.Configure(Configure);
})
;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
private void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddResponseCaching();

Expand Down Expand Up @@ -64,11 +84,11 @@ public void ConfigureServices(IServiceCollection services)
// addDbContext
services.AddDbContextPool<ReservationDbContext>(options => options.UseInMemoryDatabase("Reservation"));

services.AddGoogleRecaptchaHelper(Configuration.GetSection("GoogleRecaptcha"));
services.AddGoogleRecaptchaHelper(configuration.GetSection("GoogleRecaptcha"));
services.AddTencentCaptchaHelper(options =>
{
options.AppId = Configuration["Tencent:Captcha:AppId"];
options.AppSecret = Configuration["Tencent:Captcha:AppSecret"];
options.AppId = configuration["Tencent:Captcha:AppId"];
options.AppSecret = configuration["Tencent:Captcha:AppSecret"];
});

// registerApplicationSettingService
Expand Down Expand Up @@ -96,19 +116,15 @@ public void ConfigureServices(IServiceCollection services)
{
options.AddPolicy("ReservationApi", builder => builder.RequireAuthenticatedUser());
});

// SetDependencyResolver
DependencyResolver.SetDependencyResolver(services);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
private void Configure(IApplicationBuilder app)
{
app.UseResponseCaching();

app.UseRouting();

app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseAuthentication();
app.UseAuthorization();

Expand Down

0 comments on commit d30e351

Please sign in to comment.