【问题标题】: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
【问题描述】:

只是尝试为 NET Core Web API 构建集成测试项目。 因此,我遵循了一些示例,包括这个 (https://dotnetcorecentral.com/blog/asp-net-core-web-api-integration-testing-with-xunit/),很自然地,我遇到了问题。当我运行简单的 GET 测试时,我得到一个异常: “System.InvalidOperationException : ConnectionString 属性尚未初始化。”

任何帮助将不胜感激。

【问题讨论】:

    标签: 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));
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2013-11-17
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多