views:

61

answers:

4

I need to write a unit test for some C++ code that checks for the presence of an environmental variable. I'm using MSVS 2008 and gtest as my framework. I add the environmental variable using putenv, I check the environmental variable using getevn, but I can't figure out how to remove it so that no other test will see it. I realize this is probably easy, but I can't find the answer on the internet. Thanks

+1  A: 

you can use the unsetenv function.

If vc2008 lacks this function, you can directly access the environment using getenv_s, and remove the entry manually, simulating unsetenv.

tonio
Is that actually available on Windows without using the POSIX subsystem? Google is turning up inconsistent results...
Nicholas Knight
+2  A: 

You could always fork/exec a subprocess to do just the putenv/getenv testing, and then when it terminates there isn't any stray environment left around.

Mark B
I thought of that, but was shooting for a cleaner solution
Steve
A: 

How about setting the env var to an empty string?

From cmd.exe, this works:

set SOMEVAR=something
echo %SOMEVAR%
set SOMEVAR=
echo %SOMEVAR%

Where the last one shows it has been deleted.

rubenvb
+4  A: 

Calling putenv again specifying "SOME_VAR=" as parameter will delete environment variable SOME_VAR. btw, Microsoft recommends using _putenv as putenv is deprecated.

Rajorshi
Note that at least on Solaris there's no mention of this feature in the man page.
Mark B
He is using MSVS 2008. Implies he is working on Windows. On Linux, I would use setenv and unsetenv. Don't know if Solaris has those though.
Rajorshi