Connect with SQL Server Management Studio to testcontainer created with MsSqlTestcontainer

Viewed 104

I am running test with xunit, specflow and testcontainer to create a database in memory. When Dapper executes the query, I get this error:

In docker desktop I see the database in memory:

enter image description here

enter image description here

This is the code of the test that create the database in memory:

[Given("a valid file request (.*)")]
public void GivenAValiFileUploaded()
{
    var testcontainersBuilder = new TestcontainersBuilder<MsSqlTestcontainer>()
            .WithDatabase(new MsSqlTestcontainerConfiguration
            {
                Password = "Sup3r.Str0ng.P4ss"
            });

    var testcontainersBuild = testcontainersBuilder.Build();
    testcontainersBuild.StartAsync();

    var body = GetFile(fileName);
    _scenarioContext.Set(body, "Body");
}

Does someone know how we can get the connection string of this database in memory in docker desktop or in other anywhere?

Is there a way to get this connection string from code in c# to override the connection string placed in appsettings.json (test project)?

Thank you!

1 Answers

Here is a working sample to get the connection string.

using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Containers;

var testcontainersBuilder = new TestcontainersBuilder<MsSqlTestcontainer>()
    .WithDatabase(new MsSqlTestcontainerConfiguration
    {
        Password = "Sup3r.Str0ng.P4ss"
    });

await using (var testcontainers = testcontainersBuilder.Build())
{
    await testcontainers.StartAsync(); // This can take a while
    Console.WriteLine(testcontainers.ConnectionString);
}

Also checkout the examples in the documentation.

With this value you could then create an in process environment variable or in memory application setting.

IConfiguration config = new ConfigurationBuilder()
  .AddInMemoryCollection(new []{
      new KeyValuePair<string, string>("ConnectionStrings:YourConnectionStringName",testcontainers.ConnectionString),
      // Other values or providers
   })
  .Build();
Related