Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock System Environment Variable In C#

Tags:

I want to unit test the function which creates/Updates system environment variables. So how do i test the above functions using Nunit in C#?

like image 337
VJL Avatar asked Jul 24 '16 17:07

VJL


People also ask

How to Mock Environment variables c#?

The two calls you need are: string value = Environment. GetEnvironmentVariable("variableName") Environment. SetEnvironmentVariable("variableName", "value");

How do I test environment variables?

In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%. If the variable is set, its value is displayed in the command window.

What are Javascript environment variables?

Environment variables store variables, as the name implies. The values or things that get assigned to these variables could be API keys that you need to perform certain requests or operations. To create an environment variable, all you need to do is create a new file called .


1 Answers

Wrap the real calls that create/update the environment variables in class that can be dependency injected into your code. The two calls you need are:

string value = Environment.GetEnvironmentVariable("variableName")

Environment.SetEnvironmentVariable("variableName", "value");

This latter always takes a string as the value.

Then the wrapper class will look something like this:

class MyEnvironment
{
    public string GetVariable(string variableName)
    {
        return Environment.GetEnvironmentVariable(variableName);
    }

    public void SetVariable(string variableName, string value)
    {
        Environment.SetEnvironmentVariable(variableName, value);
    }
}

Then in your test suite inject the mock class that simulates the creation/updating. This will test the logic of your code.

The mocked class will look something like this:

class MockEnvironment
{
    private Dictionary<string, string> _mockEnvironment;

    public string GetVariable(string variableName)
    {
        return _mockEnvironment[variableName];
    }

    public void SetVariable(string variableName, string value)
    {
        // Check for entry not existing and add to dictionary
        _mockEnviroment[variableName] = value;
    }
}

You need to test the wrapper class to make sure that it does actually create/update system environment variables, but you only need to do that the once.

like image 97
ChrisF Avatar answered Sep 17 '22 17:09

ChrisF