24

I have got a method that I am trying to test which uses environment variables from my "local.settings.json"

private static string _environmentVar = Environment.GetEnvironmentVariable("environmentVarConfig");
    
public string MyMethod()
{
    var result = DoStuff(_environmentVar)
    return result;  
}

In my test I am calling this method and when debugging, I can see that _environmentVar is null.

Do I need to setup envirnomentVarConfig in the test? If so how?

10
  • 1
    Why do you think local.settings.json is going to be read and populated into an environment variable? Commented Aug 5, 2019 at 13:23
  • 1
    I'm just curious why you think that putting something in a .json file is going to lead to it becoming an environment variable. It's not impossible - you could have some code you're not showing us that does just that. But it's not going to do it out of the box. If you need to read configuration from a file, you need to use a specialized class that does just that. Environment.GetEnvironmentVariable doesn't do that. Commented Aug 5, 2019 at 13:28
  • 1
    You mean when running the application not as a unit test? Do you have additional code there that reads the configuration? Perhaps in a Startup.cs file? Commented Aug 5, 2019 at 13:31
  • 1
    Then how would the app know about your local.settings.json file? Did you look at Program.cs, in the main method? What does that call? If this is an ASP.NET Core app, you're setting up the configuration somewhere most likely, especially if you used the built in templates to create the app. Commented Aug 5, 2019 at 13:34
  • 1
    Hang on - so this is an Azure Function? Not ASP.NET Core web application? Why did you tag it as ASP.NET Core then? Commented Aug 5, 2019 at 13:37

3 Answers 3

44

Solved this by setting up the variable in the test using:

Environment.SetEnvironmentVariable("environmentVarConfig", "environmentVarValue");
Sign up to request clarification or add additional context in comments.

5 Comments

Just a note: May not work for machine wide variables that needs restart
This didn't seem to work for me (using XUnit + .net5) so I made a wrapper class & interface which I then mocked...
Working for xunit on a local laptop
This has side effects for further tests
Works on .net6. Very much appreciated.
14

You can specify environment variables in the .runsettings file:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
    <RunConfiguration>
        <EnvironmentVariables>
            <YOUR_VARIABLE>Value for your variable</YOUR_VARIABLE>
            <SOME_OTHER_VARIABLE>With another Value</SOME_OTHER_VARIABLE>
        </EnvironmentVariables>
    </RunConfiguration>
</RunSettings>

Alternatively you can implement a DataCollector which provides environment variables via ITestExecutionEnvironmentSpecifier

// Add a reference to nuget package `Microsoft.TestPlatform.ObjectModel`
// The assembly name must end with `Collector` (i.e. match `*collector.dll`)

[DataCollectorFriendlyName("my own example collector")]
[DataCollectorTypeUri("datacollector://myown/examplecollector/1.0")]
public class MyDataCollector : DataCollector, ITestExecutionEnvironmentSpecifier
{
    public override void Initialize(
        XmlElement configurationElement,
        DataCollectionEvents events,
        DataCollectionSink dataSink,
        DataCollectionLogger logger,
        DataCollectionEnvironmentContext environmentContext)
    {
        // inspect configurationElement for your custom settings
    }

    public IEnumerable<KeyValuePair<string, string>> GetTestExecutionEnvironmentVariables()
    {
        return new Dictionary<string, string>
        {
            ["YOUR_VARIABLE"] = "your value",
        };
    }
}

You also configure your data collector via the .runsettings file:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
    <RunConfiguration>
        <TestAdaptersPaths>path/where/to/find/your/collector</TestAdaptersPaths>
    </RunConfiguration>
    <DataCollectionRunSettings>
        <DataCollectors>
            <DataCollector friendlyName="my own example collector" uri="datacollector://myown/examplecollector/1.0">
                <Configuration>
                    <SomeSettingHere/>
                </Configuration>
            </DataCollector>
        </DataCollectors>
    </DataCollectionRunSettings>
</RunSettings>

3 Comments

I've added .runsettings in the project root directory, not in the solution. It didn't work until I manually pointed the location of the file. Test explorer > settings (cog icon) > Configure run settings > Select solution wide .runsettings file.
The documentation I linked gives various ways how you can set up VS to pick up the .runsettings file
Note this only works on Windows at the moment as the macOS Visual Studio doesn't yet support runsettings files.
1

I was able to do it globally for tests on WebHostBuilder according to documentation https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#set-the-environment

protected override IWebHostBuilder CreateWebHostBuilder() =>
       base.CreateWebHostBuilder().UseEnvironment("Testing");

1 Comment

this is just setting the Environment name, not setting the Environment variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.