I am using this ICollectionFixture setup
[CollectionDefinition("BaseCollection")]
public class Collection : ICollectionFixture<TestContext>
{ }
The TestContext is setup like this:
public TestContext()
{
var builder = new ConfigurationBuilder().
SetBasePath(Environment.CurrentDirectory).
AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).
AddEnvironmentVariables();
Configuration = builder.Build();
var serviceCollection = new ServiceCollection();
var connectionString =
Configuration.GetConnectionString("MyDbContext") ??
Configuration.GetValue<string>("Values:MyDbContext") ??
Configuration.GetValue<string>("MyDbContext") ??
Environment.GetEnvironmentVariable("MyDbContext");
serviceCollection.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);
ServiceProvider = serviceCollection.BuildServiceProvider();
}
The Test class looks like this:
[Collection("BaseCollection")]
public class MyIntegrationTestClass
{
private readonly MyDbContext context;
public MyIntegrationTestClass(TestContext testContext)
{
this.context = testContext.ServiceProvider.GetService<MyDbContext>();
}
}
My Azure DevOps pipeline variables:

Note that I have the following step in my YAML:
steps:
- script: echo Building with PR using ConnectionString '$(MyDbContext)'
The result from this is this print:
echo Building with PR using ConnectionString '***'
The conclusion I have drawn from this is that the environment variable is found in the pipeline but somehow not in the TestContext.
For some reason the environment variables are always null, if I use my local.settings.json it works fine. The only step in my pipeline that does not work is the test part (build, restore, pack and publish works fine). Any ideas?

ConfigurationBuilder.AddEnvironmentVariables()and the other APIs, to make sure it works as you think it does? With a console app, you can set Visual Studio's debug options to set the environment variables for debugging, and then step through the code to see what values are in the configuration objects to better understand why it's not getting the value you expect. - zivkanvar builder = new ConfigurationBuilder().AddEnvironmentVariables();,var configuration = builder.Build();,Console.WriteLine("Username = " + configuration["USERNAME"]);, and it worked just fine. It would be helpful if you could better explain what part specifically isn't working (is the value there in the TestContext constructor, or is the problem with the value returned fromtestContext.ServiceProvider.GetService<MyDbContext>()? Maybe you need to make more effort to isolate the issue? - zivkan_. - jessehouwing