xUnit 测试服务器 MVC 核心

xUnit TestServer MVC CORE

我正在尝试设置一个测试来获取我的所有产品,但我正在获取并且 ArgumentNullException 但我不明白为什么,我最近开始研究这个所以...

这是错误信息

Message: System.ArgumentNullException : Value cannot be null.
Parameter name: connectionString

private readonly TestServer server;
private readonly HttpClient client;

public ProductControllerIntegrationTests()
{
    server = new TestServer(new WebHostBuilder()
        .UseStartup<Startup>());
    client = server.CreateClient();
}

[Fact]
public async Task Product_Get_All()
{
    var response = await client.GetAsync("/api/Products");
    response.EnsureSuccessStatusCode();
    var responseString = await response.Content.ReadAsStringAsync();
    var products = JsonConvert.DeserializeObject<IEnumerable<Product>>(responseString);
    products.Count().Should().Be(12);
}

提前致谢!

Message: System.ArgumentNullException : Value cannot be null. Parameter name: connectionString

此错误是由于您在打包TestServer时没有指定配置造成的。在产品项目中,Program.cs中的WebHost.CreateDefaultBuilder(args)会配置load Microsoft.Extensions.Configuration.IConfiguration from 'appsettings.json'

如果您想在生产环境中进行测试 appsettings.json,您可以像下面这样尝试:

        public ProductControllerIntegrationTests()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        server = new TestServer(new WebHostBuilder()
            .UseConfiguration(configuration)
            .UseStartup<Startup>()
            );
        client = server.CreateClient();
    }