Omar AMEZOUG
Omar AMEZOUG

Reputation: 998

Retrieving connection string in integration test

I am trying to do some integration tests for my asp.net Core 2.1 project.

I initialise on startup file my connection string but when i run the test it still empty in handler, what is wrong on my code?

    [TestMethod]
    public async Task Method1()
    {
        var webHostBuilder = new WebHostBuilder()
                            .UseEnvironment("Development") 
                            .UseStartup<Startup>(); 
        HttpRequestMessage getRequest = new HttpRequestMessage(HttpMethod.Get, "api/action")
        {                
        };
        getRequest.Headers.Add("userId", "4622");
        getRequest.Headers.Add("clientId", "889");

        using (var server = new TestServer(webHostBuilder))
        using (var client = server.CreateClient())
        {
            var result = await client.SendAsync(getRequest);  
            ...             
        }
   }

Startup

public Startup(IConfiguration configuration)
{
        Configuration = configuration;

}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<SqlConfig>(options =>
    {
       options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
    });
    ...
}

SqlConfig

public class SqlConfig
{
    public string ConnectionString { get; set; }
}

Repository

public abstract class SqlServerQueryHandler<TQuery, TResult> : BaseQueryHandler<TQuery, TResult>
     where TQuery : IQuery<TResult>
{
   public SqlServerQueryHandler(IOptions<SqlConfig> connectionString)
    {
        this.ConnectionString = connectionString.Value.ConnectionString;
    }

   protected string ConnectionString { get; }
}

Upvotes: 0

Views: 469

Answers (1)

Omar AMEZOUG
Omar AMEZOUG

Reputation: 998

what solve my probleme is the following code :

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration, IHostingEnvironment env) : base(configuration)
    {
        var builder = new ConfigurationBuilder()
           .SetBasePath(env.ContentRootPath)
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
           .AddEnvironmentVariables();
        this.Configuration = builder.Build();
    }

Include the appsettings.json via interface on the output directory

Upvotes: 1

Related Questions