【问题标题】:XUnit Net Core Web API Integration Test: "The ConnectionString property has not been initialized."XUnit Net Core Web API 集成测试:“ConnectionString 属性尚未初始化。”
【发布时间】:2021-11-11 18:23:45
【问题描述】:
【问题讨论】:
标签:
integration-testing
asp.net-core-webapi
xunit
【解决方案1】:
对于server = new TestServer(new WebHostBuilder().UseStartup<Startup>());,需要像手动配置appsettings.json路径
var server = new TestServer(WebHost.CreateDefaultBuilder()
.UseContentRoot(@"D:\Edward\SourceCode\AspNetCore\Tests\IntegrationTestMVC")
// This is the path for project which needs to be test
.UseStartup<Startup>()
);
为了方便起见,我建议你试试Basic tests with the default WebApplicationFactory。
WebApplicationFactory 构造函数通过在包含集成测试的程序集上搜索 WebApplicationFactoryContentRootAttribute 来推断应用内容根路径,其键等于 TEntryPoint 程序集 System.Reflection.Assembly.FullName。如果未找到具有正确键的属性,WebApplicationFactory 将返回搜索解决方案文件 (*.sln) 并将 TEntryPoint 程序集名称附加到解决方案目录。应用根目录(内容根路径)用于发现视图和内容文件。
参考:How the test infrastructure infers the app content root path
【讨论】:
-
谢谢,这让我与这里的讨论一起走上正轨:github.com/aspnet/Hosting/issues/1191 我使用了 WebHost.CreateDefaultBuilder() 和 .UseContentRoot("approjectpath") ,它似乎正在使用 appsettings。 json 现在用于 API 项目,所以我能够测试真正的基础设施(API/EF 核心/数据库)
【解决方案2】:
我必须在派生的WebApplicationFactory 中覆盖CreateHostBuilder 才能添加连接字符串的配置(因为它是从用户机密中读取的)。
public class CustomApplicationFactory : WebApplicationFactory<Sedab.MemberAuth.Startup>
{
protected override IHostBuilder CreateHostBuilder()
{
var initialData = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("ConnectionStrings:DefaultConnection", "test")
};
return base.CreateHostBuilder().ConfigureHostConfiguration(config => config.AddInMemoryCollection(initialData));
}
}