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.
source share