增加支持Autofac的http单元测试

fix issue #I50DRR
This commit is contained in:
yubaolee 2022-03-31 23:50:04 +08:00
parent 21c1f67d63
commit c19802eb55
6 changed files with 153 additions and 2 deletions

View File

@ -5,8 +5,10 @@ namespace OpenAuth.App.SSO
public class PassportLoginRequest
{
/// <example>System</example>
public string Account { get; set; }
/// <example>123456</example>
public string Password { get; set; }
/// <summary>

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.Linq;
using Autofac.Extensions.DependencyInjection;
@ -27,7 +27,11 @@ namespace OpenAuth.App.Test
serviceCollection.AddOptions();
//读取OpenAuth.WebApi的配置文件用于单元测试
var path = AppContext.BaseDirectory;
int pos = path.LastIndexOf("OpenAuth.");
int pos = path.IndexOf("OpenAuth.App");
if (pos == -1) //如果测试入口是OpenAuth.WebApi
{
pos = path.IndexOf("OpenAuth.WebApi");
}
var basepath = Path.Combine(path.Substring(0,pos) ,"OpenAuth.WebApi");
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(basepath)

View File

@ -29,6 +29,7 @@
<PackageReference Include="log4net" Version="2.0.12" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="3.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.0" />

View File

@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
namespace OpenAuth.WebApi.Test
{
/// <summary>
/// Based upon https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/test/integration-tests/samples/3.x/IntegrationTestsSample
/// </summary>
/// <typeparam name="TStartup"></typeparam>
public class AutofacWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseServiceProviderFactory(new CustomServiceProviderFactory());
return base.CreateHost(builder);
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace OpenAuth.WebApi.Test
{
/// <summary>
/// Based upon https://github.com/dotnet/aspnetcore/issues/14907#issuecomment-620750841 - only necessary because of an issue in ASP.NET Core
/// </summary>
public class CustomServiceProviderFactory : IServiceProviderFactory<ContainerBuilder>
{
private AutofacServiceProviderFactory _wrapped;
private IServiceCollection _services;
public CustomServiceProviderFactory()
{
_wrapped = new AutofacServiceProviderFactory();
}
public ContainerBuilder CreateBuilder(IServiceCollection services)
{
// Store the services for later.
_services = services;
return _wrapped.CreateBuilder(services);
}
public IServiceProvider CreateServiceProvider(ContainerBuilder containerBuilder)
{
var sp = _services.BuildServiceProvider();
#pragma warning disable CS0612 // Type or member is obsolete
var filters = sp.GetRequiredService<IEnumerable<IStartupConfigureContainerFilter<ContainerBuilder>>>();
#pragma warning restore CS0612 // Type or member is obsolete
foreach (var filter in filters)
{
filter.ConfigureContainer(b => { })(containerBuilder);
}
return _wrapped.CreateServiceProvider(containerBuilder);
}
}
}

View File

@ -0,0 +1,80 @@
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Autofac;
using Infrastructure;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using OpenAuth.App;
using OpenAuth.App.SSO;
namespace OpenAuth.WebApi.Test
{
/// <summary>
/// 模拟HTTP请求测试
/// 用于测试模型绑定看看一次客户端的请求是否能被正确解析亦或者测试WebAPI入口的一些Filter AOP等是否被正确触发。
/// 详情参考https://www.cnblogs.com/yubaolee/p/DotNetCoreUnitTest.html
/// </summary>
public class TestHttpRequest
{
private HttpClient _client;
void ConfigureTestServices(IServiceCollection services)
{
}
void ConfigureTestContainer(ContainerBuilder builder)
{
AutofacExt.InitAutofac(builder);
}
[SetUp]
public void Init()
{
var factory = new AutofacWebApplicationFactory<Startup>();
_client = factory
.WithWebHostBuilder(builder => {
builder.ConfigureTestServices(ConfigureTestServices);
builder.ConfigureTestContainer<ContainerBuilder>(ConfigureTestContainer);
})
.CreateClient();
}
/// <summary>
/// 模拟一次登录
/// </summary>
[Test]
public LoginResult TestLogin()
{
var loginreq = new PassportLoginRequest
{
Account = "System",
Password = "123456",
AppKey = "openauth"
};
var request = new StringContent(JsonHelper.Instance.Serialize(loginreq));
request.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = _client.PostAsync("http://localhost:52789/api/Check/Login", request);
string result = response.Result.Content.ReadAsStringAsync().Result;
var loginresult = JsonHelper.Instance.Deserialize<LoginResult>(result);
Console.WriteLine($"登录结果:{result}");
return loginresult;
}
/// <summary>
/// 模拟加载字典列表
/// </summary>
[Test]
public void TestLoad()
{
_client.DefaultRequestHeaders.Add("X-Token", TestLogin().Token);
var response = _client.GetAsync("http://localhost:52789/api/categorys/load?page=1&limit=20");
string result = response.Result.Content.ReadAsStringAsync().Result;
Console.WriteLine($"获取分类列表:{result}");
}
}
}