Friday, October 12, 2007

NUnit configuration woes

I've been going through writing NUnit tests for a .NET web app I'm writing at work and all was going well until I hit some code that was using the ConfigurationManager.

1 private static readonly string CONNECTION_STRING =
2  ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;

For backgrounds sake I've created a test dll that sits outside the web app that calls a dll used by the web app. The connection string information is stored in Web.config.

Whenever NUnit loaded up the tests requiring that connection it barfed this at me:

Test.TestDataAccessUtility.GetNameValueTOList : System.TypeInitializationException : The type initializer for 'DataAccessUtility' threw an exception.
----> System.NullReferenceException : Object reference not set to an instance of an object.


Nice, this essentially means that ConfigurationManager had crapped itself.

ConfigurationManager.ConnectionStrings.Count was returning 1.

ConfigurationManager.ConnectionStrings[0].ConnectionString sent back a conn string for a SQLExpress db with some configuration string I sure didn't set.

It would appear that the NUnit loads it's config file over your application's config file.

To fix, I just replaced the contents of the NUnit config file: Project1.config with the contents of my Web.config. There could be a better solution, but it's working now and I can move on with my life.

2 comments:

Unknown said...

Howdy,

I'm having a similar issue where NUNIT refuses to see my config file. It tells me that there is a system.nullreferenceexception : Object reference not set to an instance of an object. However the code runs fine in the web application.

Can you tell me if you have seen this, or have a solution other than the one you wrote about?

dan said...

Hi bing

That was pretty much the issue I was having.

The way I'm currently handling it is as follows:

1. Have an App.config in the test assembly that specifies the appSettings needed.

2. Have an auto post-build event fire when the test assembly gets built that copies the App.config file to the target running directory. i.e.

copy /Y "$(ProjectDir)App.config" "$(TargetDir)$(TargetFileName).config"

Let me know how you get on with it.

Cheers