且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XUnit Net Core Web API集成测试:"ConnectionString属性尚未初始化."

更新时间:2023-02-14 17:45:19

对于server = new TestServer(new WebHostBuilder().UseStartup<Startup>());,您需要手动配置appsettings.json路径,例如

For server = new TestServer(new WebHostBuilder().UseStartup<Startup>());, you need to manually configure the appsettings.json path like

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>()
    );

为方便起见,建议您尝试使用默认WebApplicationFactory 的基本测试.

For a convenience way, I would suggest you try Basic tests with the default WebApplicationFactory.

WebApplicationFactory构造函数通过在包含集成测试的程序集上搜索WebApplicationFactoryContentRootAttribute来推断应用程序内容的根路径,该程序包含与TEntryPoint程序集System.Reflection.Assembly.FullName相等的键.如果找不到具有正确键的属性,则WebApplicationFactory会后退以搜索解决方案文件(* .sln),并将TEntryPoint程序集名称附加到解决方案目录中.应用程序的根目录(内容根目录路径)用于发现视图和内容文件.

The WebApplicationFactory constructor infers the app content root path by searching for a WebApplicationFactoryContentRootAttribute on the assembly containing the integration tests with a key equal to the TEntryPoint assembly System.Reflection.Assembly.FullName. In case an attribute with the correct key isn't found, WebApplicationFactory falls back to searching for a solution file (*.sln) and appends the TEntryPoint assembly name to the solution directory. The app root directory (the content root path) is used to discover views and content files.

参考: 查看全文