Can you set temporary environment variables for MSTest Run Configurations?

I am using MSTest in Visual Studio 2008 with C #. I have a special environment variable that I would like, and a path change that I would like to make only during the execution of any specific tests, or even better, but all the tests are in the launch configuration.

I tried using the test run configuration of the Setup script to do this, but, as I expected, since this is a batch file, the changes are lost after it exits, so this will not work.

Is there any other way to set temporary system environment variables that will be valid during all running tests?

+6
source share
2 answers

Until I was happy with this solution, I managed to get what I needed to do with MSTest using the ClassInitializeAttribute for the test class, and then using Environment.SetEnvironmentVariable to make the necessary changes and then clear its method decorated with the ClassCleanupAttribute attribute.

With the lack of a better answer, this was the way I was able to get the environment variables set for the test group and clear them when I finished. However, I would prefer it to be processed outside of CODE and somehow be part of the test configuration. No matter what problems have been resolved.

+5
source

If you trust that your test suite will not be โ€œinterruptedโ€ in the middle of the test, you can use the FixtureSetup and FixtureTeardown methods to set and delete the changed environment variables.

EDIT FROM COMMENTS . I see where you came from, but, like in my editing, the UT framework is not used to create unit tests. The concept of unit test dictates that it should NOT depend on any external resources, including environment variables. The tests that do this are integration tests and require that most of the infrastructure is in place (and usually takes many times more than a unit test set equal to LOC).

To create a unit test for code that depends on an environment variable, consider splitting lines of code that directly test environment variables directly. and put this in a method in another class, then mock this class with RhinoMocks or some other way to provide a โ€œdummyโ€ value for testing without examining (or changing) the actual environment variables.

If this is really an integration test, and you really need an environment variable (let's say you change the path so you can use Process.Start to call your own notepad.exe instead of Windows), then what FixtureSetup and FixtureTeardown methods / attributes; to perform complex setups of a fixed, repeatable environment in which tests must succeed, and then reset the environment as it was, regardless of what happened in the tests. Typically, a test failure throws an exception and terminates the test immediately, so the code at the end of the test method itself is not guaranteed.

+1
source

Source: https://habr.com/ru/post/889973/


All Articles