.Net Core 5 Web Api - Xunit 没有读取我的 appsettings.Development

.Net Core 5 Web Api - Xunit not reading my appsettings.Development

我开始从我的 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();
        }...

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

Load your settings IConfigurationBuilder 在你的 Startup 中。您可以通过 AddJsonFile 方法指定相对路径。

还有你真的需要在你的单元测试中启动一个服务器吗?您测试 class 功能,它很少需要 运行 服务器。为了将测试设置注入 class 测试,您可以使用 the options pattern 并且在您的测试中通过 Options.Create(new MyDummySettings()).

提供虚拟设置

默认情况下,当您创建 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();
    }
}