0

I am writing a unit test project for the azure functions which is using Startup class inheriting the FunctionStartUp. In this Startup class I am loading my all dependencies and configuration with Enviornment variables loading.

Problem is while running the unit test method I am getting the Enviornment variables values as null (because Startup class was not called hence Enviornment variables are not Set).

Can anyone suggest me how load Enviornment variables which are set in local.Setting.json and appsetting.json file?

2 Answers2

0

In your unit test code, you have to set the variables using Environment.SetEnvironmentVariable("key", "value");

Chris
  • 3,113
  • 5
  • 24
  • 46
0

To add some information on top of Chris's answer. You can refer to this post How to get environment variable in Xunit Test

It seems pretty forward to me to implement this. You just have to create another class, that will be shared by all other classes. In Xunit they called it Fixture. See link Shared context between test

In this class, I will read my config file from my target testing project, and set the environment variables. See link How to get environment variable in Xunit Test

Code sample

public class SharedDataFixture: IDisposable
{
    public SharedDataFixture()
    {
        using (var file = File.OpenText("D:\\TargetProject\\local.settings.json"))
        {
            var reader = new JsonTextReader(file);
            var jObject = JObject.Load(reader);

            var variables = jObject.GetValue("Values").ToString();
            var keyValuePairs = JsonConvert.DeserializeObject<Dictionary<string, string>>(variables);


            foreach (var pair in keyValuePairs)
            {
                Environment.SetEnvironmentVariable(pair.Key, pair.Value);
            }
        }

        string keyVaultName = System.Environment.GetEnvironmentVariable("AZURE_KEY_VAULT");

        //Retrieving my json values using environment variable set
        azureLoginInfo = new AzureLoginInfo(keyVaultName);

        // ... other data
    }

    public void Dispose()
    {
        // ... clean up test data from the database ...
    }

    public AzureLoginInfo azureLoginInfo  { get; private set; }
}

My Xunit testing class (I modified a little to adjust it to my usage):

public class CreateAzureResourcesTests : IClassFixture<SharedDataFixture>
{
    AzureLoginInfo azureLoginInfo;

    public CreateAzureResourcesTests (SharedDataFixture fixture)
    {
        this.fixture = fixture;
    }

    // ... write test ...
}
csamleong
  • 769
  • 1
  • 11
  • 24