我有一个集成测试项目,它在测试类中使用.UseSetting()
,如下所示:
public AccessTokenRetrieval() : base(nameof(AccessTokenRetrieval))
{
var connectionString = GetConnectionString();
var dbSettings = new DbSettings(connectionString);
_userGroupRepository = new UserGroupRepository(dbSettings);
_roleRepository = new RoleRepository(dbSettings);
_userRepository = new UserRepository(dbSettings);
_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>()
.UseEnvironment("IntegrationTest")
.UseSetting("IntegrationTestConnString", dbSettings.IdentityServerConnectionString));
_handler = _server.CreateHandler();
_client = _server.CreateClient();
}
我现在想在实际项目的startup.cs中检索该设置。我试图使用:
public void ConfigureIntegrationTestServices(IServiceCollection services)
{
var connectionString = Configuration.GetValue<string>("IntegrationTestConnString");
BuildIdentityServerTests(services, connectionString);
AddCoreServices(services, connectionString);
}
但这似乎会返回空值。
检索此设置的正确方法是什么?
最佳答案
每个测试设置
要将设置传递到特定的TestHost
实例,可以使用ConfigureServices
调用并覆盖默认设置注册。
首先,在DbSettings
方法中注册默认的Startup.ConfigureServices
实例。必须使用TryAll
调用:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton(new DbSettings(...));
}
}
在
WebHostBuilder.ConfigureServices
调用中注册模拟实例:_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>()
.ConfigureServices(services =>
{
services.AddSingleton(new DbSettings(...));
}
);
当您试图解析应用程序代码中的
DbSettings
时,您将得到一个模拟实例。因为WebHostBuilder.ConfigureServices
首先执行,而TryAdd
调用阻止注册默认实例。此提示允许替换您注册的任何DI依赖项。
全局设置
要设置不变量(accross all tests)设置,请设置进程范围的环境变量,而不是
UseSetting
调用:Environment.SetEnvironmentVariable("foo", "bar");
var _server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>()
);
然后阅读:
public void ConfigureServices(IServiceCollection services)
{
string setting1 = Configuration["foo"];
string setting2 = Environment.GetEnvironmentVariable("foo");
}
您需要添加环境变量提供程序以从
Configuration
读取变量:public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
//this config provider is mandatory to read env vars from Configuration
.AddEnvironmentVariables();
Configuration = builder.Build();
}