Using Settings in Test Projects

There are many ways to enhance testing projects in your Visual Studio solution. From simple unit testing to enhanced runs with iterations that supply different data, the testing environment is a fully compiled class that can be customized and leverage the .NET framework BCLs. One instance where you can use this capability is to avoid hard coding in values for your code so that you don't have to change them and recompile the test each time. By leveraging the Settings within the testing project, you can create a settings.settings file (basically a configuration file which holds setting sections for the application) and then refer to those within the code. This can be done with full intellisense support once you write the settings into the settings file.

For example, if I have a unit test which reflects the following code:

 

[TestMethod()]

public void AuthenticateUserTest()

{

AuthenticationClass target = new AuthenticationClass();

 

string userName = "MyUserName"';

string passWord = "MyPassword";

 

bool expected = true;

bool actual;

 

actual = target.AuthenticateUser(userName, passWord);

 

///Assert logic here

 

}

 

What you may notice is that the test method has hard coded values for userName and passWord as well as the expected result. If I am testing for authentication success, this is great. However, if I want to test failure, I have to then go back into the code and reset the hard coded values. Alternatively, you can draw these values from the settings file.

 

 

[TestMethod()]

public void AuthenticateUserTest()

{

AuthenticationClass target = new AuthenticationClass();

 

string userName = Properties.Settings.Default.UserName.ToString();

string passWord = Properties.Settings.Default.UserName.ToString();

 

bool expected = Convert.ToBoolean(Properties.Settings.Default.ExpectedResult);

bool actual;

 

actual = target.AuthenticateUser(userName, passWord);

 

///Assert logic here

 

}

 

In this manner, you can now use the settings designer to create and modify the Settings.Settings file (located under the project properties) to type in your settings and save them as part of the config file for the project. The really nice thing here is that you receive full Intellisense on the properties you define in that file. Now you r tests are easier to maintain and you can change them for a variety of situations. For additional code coverage, you can even data drive your unit tests by having them loop over data sets from a database.