19

Seems like a pretty trivial question, but to my surprise I found no mention of this on the web.

I've got an Nunit test project (that someone else wrote and I don't want to change too much), that I need to debug. These tests depend on environment variables that they read using Environment.GetEnvironmentVariable.

My question is: is there a way I can pass environment variables when debugging tests in Visual Studio?

I know I can pass environment variables when I debug an executable project through Project Properties->Debug, but this doesn't take effect when running tests (e.g. via Test Explorer). I also know I can pass test parameters through a .runsettings files, but these are accessible only through the TestContext class.

Arnon Axelrod
  • 1,444
  • 2
  • 13
  • 21
  • Hi, any update about this issue? If my answerr helps you handle the issue, please do not accept it. And if not, please feel free to let us know:) – Mr Qian Oct 05 '20 at 03:38
  • I'm facing the same situation. Some integration tests executed in Jenkins, which injects environment variables for connection strings and other things, do not work from the VS Test Explorer, unless I specifically modify my system environment variables, just to be able to run the tests (In my case the reason why it was done this way, was to prevent credentials being kept in source or config files) – Nelson Rodriguez Apr 23 '21 at 15:51

2 Answers2

11

I also know I can pass test parameters through a .runsettings files, but these are accessible only through the TestContext class.

You can also 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 (if you need to run code or calculate the value) 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>
Zarat
  • 2,584
  • 22
  • 40
-1

If you want to change the environment vaiable when you are debugging a project without break it, you can try to set it in the system environment variable.

1), create a system environment variable called number

enter image description here

2) use this in your code:

string str=  Environment.GetEnvironmentVariable("number",EnvironmentVariableTarget.Machine);

It will get the system environemnt variable number in your code.

3) start debugging this project and set a breakpoint on it, when you want to change the variable, you can change the value on the system environemnt variable number directly under Computer's properties.

After that,just move the cursor back to the code line, you can use the changed value.

=========================================

Update 1

enter image description here

When you change the value of system variable number, you should click OK to save the new value. And then move the cursor of the breakpoint back to get the new value.

Also, you should enable Edit and Continue option.

Mr Qian
  • 21,064
  • 1
  • 31
  • 41
  • 2
    Thanks @Perry. This solution obviously works and may even be the only possible solution, but it sucks. It means that I must set the environment variable as a system-wide variable, and not only for the debugged process (as I can do when I debug a console app for example) – Arnon Axelrod Oct 05 '20 at 09:35
  • 1
    Sorry, I just checked it and it *doesn't* work. I guess that it will work only if you set the variable before opening Visual Studio! If I need to close and reopen VS each time I need to change the value, that this is not a viable solution for me after all :-( – Arnon Axelrod Oct 05 '20 at 09:59
  • If my side, when I change the variable of the system number, I can get the changed value. I will update a small gif for you. – Mr Qian Oct 08 '20 at 09:59
  • In my test, I did not break the debugging process and did not have to restart VS. Just enable `Edit and Continue` vs option. – Mr Qian Oct 08 '20 at 10:03
  • 2
    What you show is a console application project. I'm talking about Nunit test project. In this type of project it doesn't work... – Arnon Axelrod Oct 14 '20 at 06:54