c# - xUnit TestServer MVC 核心

标签 c# testing asp.net-core xunit fact

我正在尝试设置一个测试来获取我的所有产品,但我得到了 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 。在产品项目中,WebHost.CreateDefaultBuilder(args)Program.cs将配置从“appsettings.json”加载 Microsoft.Extensions.Configuration.IConfiguration

如果您想使用生产 appsettings.json 进行测试,您可以尝试如下:

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

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

关于c# - xUnit TestServer MVC 核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175709/

相关文章:

c# - 如果属性中有验证属性,为什么 Validator.TryValidateObject 不验证类?

c# - 为什么 Request.QueryString.Get() 和 NameValueCollection.Get() 返回解码值?

c# - SQL Server CE 回滚不会撤消删除

node.js - Protractor JS 预处理器

python - 单元测试 Python Flask Stream

ASP.NET vNext 上的 ELMAH?

c# - .net C# 中的 AES 128 ECB 解密

npm - 如何使 project.json 脚本的构建失败

.net - Asp.Net Core 1.0 和.Net Core 1.0 之间的区别?

java - 为什么在尝试使用 Selenium 打开网站时出现 GridException