Using web.config application settings in nUnit

If the piece of code that you are testing refers to an appsetting value in the web.config file then nUnit will fall over – basically because nUnit itself does not use the web.config file.

This is a fairly common thing to come up against, and the easy solution is on the web, but it doesn’t appear to be in the nUnit help so I thought I’d put it here too, and make it specific to the dependency injection/Sharp Architecture web projects that my team use.

There are two things that you can do. The quick thing to do is to find your tests dll file. In a Sharp Architecture 1.6 project this will be in something like [project root]/tests/[namespace].Tests/bin/Debug. The dll file will be called (unsurprisingly) [namespace].Tests.dll.

You will see that nUnit has also created a [namespace].Tests.dll.config file. This is where you should put your application settings. When you open it up you can see that it looks similar to the web.config file – there is already an appsettings section. Simply copy your web.config settings to here.

That is all very well, but what if you want to mock different values of this app setting when you are testing? If you are using a dependency injection development pattern you might also want to consider having a separate class and interface that just handles the retrieval of application settings, e.g.

public class AppSettingsService: IAppSettingsService
{
        public string ManagerRole
        {
            get { 
              if (ConfigurationManager.ConnectionStrings["ManagerRole"] == null)
                 return "";
              else
                 return ConfigurationManager.ConnectionStrings["ManagerRole"].ToString();  
            } 
        }
}

You can then inject this service class into the class that you are testing, use the methods on this service class to retrieve your appsettings, and mock them to your heart’s content.

Note: I am assuming you know what dependency injection, mocking, interfaces etc are. If not I suggest searching the net – they are a very good way of developing!