Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use environment variables in unit tests (.net core)

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("envirnomentVarConfig");

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?

like image 596
ayo1234 Avatar asked Aug 05 '19 13:08

ayo1234


People also ask

How do you set an environment variable in the NET Core console app?

With all these packages installed, I could initialize the ConfigurationBuilder with a subset of the default ASP.NET Core setup: var environment = Environment. GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var builder = new ConfigurationBuilder() . AddJsonFile($"appsettings.

How do you pass an environment variable?

Environment variables can be used to pass configuration to an application when it is run. This is done by adding the definition of the environment variable to the deployment configuration for the application. To add a new environment variable use the oc set env command.


3 Answers

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

Environment.SetEnvironmentVariable("environmentVarConfig", "environmentVarValue");
like image 163
ayo1234 Avatar answered Oct 17 '22 07:10

ayo1234


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>
like image 36
Zarat Avatar answered Oct 17 '22 05:10

Zarat


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");
like image 1
Ľuboš Pilka Avatar answered Oct 17 '22 05:10

Ľuboš Pilka