Monday, July 18, 2005

Using Configuration Files in NUnit

Using configuration file for NUnit is similar to web.config file in ASP.NET web application and application.config for executables.

What will you do when NUnit requires a .DLL assembly and your code has been written to use a configuration file? The answer is that you will create a configuration file for testing using NUnit J.

NUnit creates an instance of the AppDomain for the .DLL you are testing. One of the other things it does is to manually look for an assembly.dll.config file. Thus, if you need configuration options for your application, copy those settings into a .config file for testing. In our example, such a .config file would be MyDll.dll.config, placed in the same directory as the test DLL loaded by NUnit.

Lets say I have a method bool IsNum(string val) in my MyDLL class (MyDll.dll) which takes a string as parameter and if the string is a number is will return true else false.

What I want is that I create generic test using NUnit and different values passed to my IsNum method to test should be read from the config file. The test should be performed as many times as there are test values in my configuration file. So tomorrow if I want to pass a new value to see if my method is working correctly or not I just need to add a new entry in the config file.

This is my sample MyDll.dll.config file:

Place this config file with your test dll.

Now my Test method will look like:

public void ValidateNumberTest()
NameValueCollection nvc = (NameValueCollection) ConfigurationSettings.GetConfig("ValidateNumberTest");
MyDll d = new MyDll();
string val = "";
for(int i=0;i< nvc.Count;i++)
val = nvc.Get(i);

I know this sample is not a great one but I think it gives a fair Idea how we can use a configuration file with NUnit.

No comments: