views:

242

answers:

3

I am running a c# unit test (VS 2008). Within the test I do write to the settings, which should result in saving the data to the user.config.

Settings.Default.X = "History"; // X is string
Settings.Default.Save();

But this simply does not create the file (I have crosschecked under "C:\Documents and Settings\HW\Local Settings\Application Data").

If I create the same stuff as a Console application, there is no problem persisting the data (same code).

Is there something special I need to consider doing this in a UnitTest?

+1  A: 

Unit Test projects are just class libraries. There's no application context and thus you may have problems because the settings object does not know what Company/Application to file the settings file under.

I am unsure, but it may just be creating it in-memory.

Aren
As test methods have to be executed, the unit-test framework will instantiate test classes in a real application context. Thus tests are executed in a directory on the file system which implies having configuration files.
Ucodia
My mistake was calling Reset() before Reload(). I was unaware that Reset() also saves in the same turn, I was thinking it resets the values only in memory.
HorstWalter
+2  A: 

I tried it with Visual Studio 2010 on Windows 7 and the Visual Studio Unit Test framework is actually creating a temporary folder for test applications in which I found my user.config file with correct settings. I think it might be the same thing on VS 2008. The path scheme to these folder is of the kind:

Windows Vista/Seven path:

C:\Users\$USER$\AppData\Local\Microsoft_Corporation\TestAppDomain{Number}

Windows XP path:

C:\Documents and Settings\$USER$\Local Settings\Microsoft_Corporation\TestAppDomain{Number}

Good luck.

Ucodia
thanks a lot, you helped me a lot. Minor tweak: its .. \Local Settings\Application Data\Microsoft_Corporation\...for XP
HorstWalter
A: 

Thanks for your help, it helped a lot finding the issue. The hint with the path helped me "seeing what is going on" and finding the troublemaker.

BTW, this snippet

 config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
 config.FilePath

is useful finding the storage location.

My problem was that I called Reset() before Reload(). Actually my test case checks whether the objects are stored correctly, so it saves and reloads the settings. I was unaware of the fact, that Reset() "resets and saves on disk" - I was assuming it only resets in memory. I must only call Reload().

Since all test cases have their own directory, the settings have to be created (saved) within the test case.

HorstWalter
This could help finding the user.config file but is not actually showing the user configuration. It is only showing the application configuration. In normal situation, application and user configuration file belongs to different directories so be careful!
Ucodia