【问题标题】:.Net Core 5 Web Api - Xunit not reading my appsettings.Development.Net Core 5 Web Api - Xunit 没有读取我的 appsettings.Development
【发布时间】:2021-07-02 05:03:01
【问题描述】:

我开始从我的 api 构建测试,为此我正在使用 xunit,但它没有读取我的 appsettings.Development.json,这是怎么回事?

namespace CorporateMembership.Test.Integration
{
    public class ContestTest
    {
        private readonly HttpClient _httpClient;

        public ContestTest()
        {
            var server = new TestServer(new WebHostBuilder()
                .UseEnvironment("Development")
                .UseStartup<Startup>());

            _httpClient = server.CreateClient();
        }...

【问题讨论】:

    标签: c# .net .net-core webapi


    【解决方案1】:

    默认情况下,当您创建TestServer 时,它不会构建配置,您需要构建配置并将其传递给测试服务器。

    public class ContestTest
    {
        private readonly HttpClient _httpClient;
    
        public ContestTest()
        {
            var environment = "Development";
            var directory = Directory.GetCurrentDirectory();
            var configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(directory)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json");
    
            var server = new TestServer(new WebHostBuilder()
                .UseEnvironment(environment)
                .UseConfiguration(configurationBuilder.Build())
                .UseStartup<Startup>());
    
            _httpClient = server.CreateClient();
        }
    }
    

    【讨论】:

    • @Allan 您的欢迎,如果您按下upvote 按钮,它会很高兴
    • 我需要 15 点声望才能点击点赞,现在我只有 3 点,抱歉 :(
    • 没问题,现在你有 13 个 ;-),如果你编辑问题并改进它们,那么你也会获得一些声誉。
    • 天哪,谢谢...我提出了一个新问题,我花了 1 天的时间尝试制作后测试用例,但没有成功:(
    【解决方案2】:

    您的测试项目可能构建在与主项目不同的目录中,因此您的 appsettings.Development.json 文件不存在。

    Load your settingsIConfigurationBuilder 在您的 Startup 中。您可以通过AddJsonFile方法在此处指定相对路径。

    你真的需要在你的单元测试中启动一个服务器吗?您测试类功能,这很少需要运行的服务器。为了将测试设置注入到类测试中,您可以使用the options pattern,然后在您的测试中通过Options.Create(new MyDummySettings()) 提供虚拟设置。

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 2018-05-10
      • 2020-02-11
      • 2018-05-08
      • 2021-12-04
      • 2021-12-14
      相关资源
      最近更新 更多