appsettings.shared.json
文件放在 Cnblogs.Bootstrapper
项目中,Cnblogs.Web
引用了 Cnblogs.Bootstrapper
项目,dotnet run
运行 Cnblogs.Web
站点时可以正常找到 appsettings.shared.json
,因为 build Cnblogs.Web
时 appsettings.shared.json
会被自动复制到 Cnblogs.Web
的 bin 文件夹中。
Cnblogs.Web.IntegrationTests
项目引用了 Cnblogs.Web
项目,在运行集成测试时却报错提示找不到 appsettings.shared.json
System.IO.FileNotFoundException : The configuration file 'appsettings.shared.json' was not found and is not optional. The expected physical path was '....../Cnblogs.Web/appsettings.shared.json'
Cnblogs.Web
与 Cnblogs.Web.IntegrationTests
的 bin 文件夹中都有 appsettings.shared.json
文件,而集成测试却在 Cnblogs.Web
的根目录中找这个文件,所以找不到。
请问如何解决这个问题?
通过 SetBasePath(Environment.CurrentDirectory)
解决了
WebAppFactory.cs 中的代码
public class WebAppFactory : WebApplicationFactory<Startup>
{
protected override IHostBuilder CreateHostBuilder() => Host.CreateDefaultBuilder()
.UseEnvironment("Testing")
.ConfigureAppConfiguration(AppConfiguration.Configure)
.ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.UseStartup<TestStartup>());
}
AppConfiguration.cs 中的代码
public static class AppConfiguration
{
public static void Configure(
HostBuilderContext hostingContext,
IConfigurationBuilder appConfigBuilder)
{
IHostEnvironment env = hostingContext.HostingEnvironment;
if (env.IsEnvironment("Testing"))
{
appConfigBuilder.SetBasePath(Environment.CurrentDirectory);
}
appConfigBuilder.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
}
}