Search code examples
c#testingasp.net-corexunitfact

xUnit TestServer MVC CORE


I am trying to setup a test for getting all my product but I am getting and ArgumentNullException but I do not get why, I recently started studying this so ...

This is the error message

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);
}

Thanks in advance!


Solution

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

    For this error, it is caused by that you did not specific the Configuration when crating TestServer. In the product project, WebHost.CreateDefaultBuilder(args) in the Program.cs will configure load Microsoft.Extensions.Configuration.IConfiguration from 'appsettings.json'.

    If you want to test with production appsettings.json, you could try like below:

            public ProductControllerIntegrationTests()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
    
            server = new TestServer(new WebHostBuilder()
                .UseConfiguration(configuration)
                .UseStartup<Startup>()
                );
            client = server.CreateClient();
        }