2

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!

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Without the stack trace it's difficult to say. My best guess would be it's throwing the exception when you're instantiating your TestServer. – amarsha4 Jul 04 '18 at 16:16

1 Answers1

2

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();
    }
Edward
  • 28,296
  • 11
  • 76
  • 121
  • I have been banging my head for the past couple of days over this issue--this solution is simple and works like a champ!! Thanks!! – Tom Miller Mar 06 '19 at 16:20