Home > Net >  Is there a good way to unit test using Environment Variables?
Is there a good way to unit test using Environment Variables?

Time:01-18

I have a couple of environment variables that are used as part of creating defaults for config options. Basically if the config options property in question is null then use the value from the specified environment variable.

I want to test the options objects correctly use the environment variable when null, so initially thought I'd just set the specified environment variable. However, this is an environment variable that will actually be used on the environment and therefore I don't really want to be messing with it. Is there a way I can wrap environment variables using an interface or something so I can mock the SetEnironmentVariable() method or something similar?

In terms of code my options objects look something like this:

public sealed record MyOptions
{
    public string SomeProperty { get; set; }

    public MyOptions()
    {
        var defaultVal = Environment.GetEnvironmentVariable("MY_VARIABLE");
        SomeProperty = SomeProperty ?? defaultVal;
    }
}

So if the SomeProperty hasn't been set via config, it will use the default value from the specified environment variable. I was thinking perhaps an EnvironmentVariableService, that retrieves all environment variables and puts them in a ConcurrentDictionary, and that's used in the place of the Environment.

CodePudding user response:

Your question contains the answer

  • Related