Search code examples
c#asp.net-web-apiweb-configintegration-testing

ConfigurationManager in ASP.NET WebAPI tested with HttpServer


I have a Web API project, which I trying to test by using in-memory hosting with HttpServer.

I've got server running, but request returns 500 InternalServerError response.
Execution fails when I try to get connection string with ConfigurationManager, during debugging I can see that ConfigurationManager.ConnectionStrings does not contain value for given key.
Instead it contains some "default" connection string.

{
    "LocalSqlServer": "data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"`
}

Web.config file contains connection string with key "my-database"

<configuration>
  <connectionStrings>
    <add name="my-database" providerName="System.Data.SqlClient" 
     connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\hotel.mdf;Integrated Security=True" />
  </connectionStrings>
</configuration>

Code where failing

public class Database
{
    public static SqlConnection CreateConnection()
    {
        var connectionString = 
            ConfigurationManager.ConnectionStrings["my-database"].ConnectionString; // Fails here with NullReference exception
        return new SqlConnection(connectionString);
    }
}

HttpServer configuration and tests

public class ServerTest : IDisposable
{
    private readonly HttpServer _server;

    public ServerTest()
    {
        var config = new HttpConfiguration();         
        WebApiConfig.Register(config); // Call configuration from system under the test
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        _server = new HttpServer(config);
    }

    public void Dispose() => _server.Dispose();

    [Fact]
    public async Task ReturnsOk()
    {
        var client = new HttpClient(_server)
        {
            BaseAddress = new Uri("http://dummy.testing.api/")
        };

        var response = await client.GetAsync("rooms");

        response.StatusCode.Should().Be(HttpStatusCode.OK);
    }
}

How I can configure HttpServer to use actual configurations(connection string)?


Solution

  • I can't be certain given the details provided, but are you running your code as a console application? It appears that maybe you're running this as some sort of xUnit test? At any rate, you might need to ensure that you have an "app.config" file (not web.config) in whatever project you're working.